gpt4 book ai didi

python - 有没有更好的方法来构建这样的列表?

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:40 24 4
gpt4 key购买 nike

我是 Python 的新手,我很喜欢它,但想知道是否有更好的方法来进行一些列表操作。

这个相对理智,但似乎我可能错过了一个内置函数。

def zip_plus(source_list, additional_list):
"""
Like zip but does plus operation where zip makes a tuple

>>> a = []
>>> zip_plus(a, [[1, 2], [3, 4]])
>>> a
[[1, 2], [3, 4]]
>>> zip_plus(a, [[11, 12], [13, 14]])
>>> a
[[1, 2, 11, 12], [3, 4, 13, 14]]
"""
if source_list:
for i, v in enumerate(additional_list):
source_list[i] += v
else:
source_list.extend(additional_list)

这篇文章很骇人听闻,有什么想法可以让它更简洁或更符合 Python 风格吗?

def zip_join2(source_list, additional_list):
"""
Pretty gross and specialized function to combine 2 types of lists of things,
specifically a list of tuples of something, list
of which the something is left untouched

>>> a = []
>>> zip_join2(a, [(5, [1, 2]), (6, [3, 4])])
>>> a
[(5, [1, 2]), (6, [3, 4])]
>>> zip_join2(a, [(5, [11, 12]), (6, [13, 14])])
>>> a
[(5, [1, 2, 11, 12]), (6, [3, 4, 13, 14])]
"""
if source_list:
for i, v in enumerate(additional_list):
source_list[i] = (source_list[i][0], source_list[i][1] + v[1])
else:
source_list.extend(additional_list)

最佳答案

def zip_plus(first, second):
return [x+y for (x,y) in zip(first, second)]

def zip_join2(first, second):
return [(x[0], x[1]+y[1]) for (x,y) in zip(first, second)]

关于python - 有没有更好的方法来构建这样的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com