我有两个清单。我想像这样加入他们:
[1, 2, 3], [1, 2, 3] => [1, 1, 2, 2, 3, 3]
[1], [2, 3] => [1, 2]
[], [1, 2, 3] => []
[4, 5, 6, 7], [1] => [4, 1]
在没有itertools?
的情况下,有没有简单的方法可以做到这一点似乎我想出了如何做到这一点:
new_list = first_list+second_list
new_list[::2] = first_list
new_list[1::2] = second_list
return new_list
但它只适用于相同长度的列表
答案 0 :(得分:5)
使用zip
将您的列表列表(您可以拥有任意数量的子列表)作为参数使用*
解包并展平项目(zip
停靠在最短的清单):
s = [1, 2, 3], [1, 2, 3]
result = [y for x in zip(*s) for y in x]
相当于(对于那些不习惯参数解包的人):
first_list = [1, 2, 3]
second_list = [1, 2, 3]
result = [y for x in zip(first_list,second_list) for y in x]
结果:
[1, 1, 2, 2, 3, 3]
使用s = [1], [2, 3]
,您可以按预期获得[1,2]
答案 1 :(得分:2)
您可以将zip
与列表理解结合使用:
>>> [x for row in zip([1, 2, 3], [1, 2, 3]) for x in row]
[1, 1, 2, 2, 3, 3]
>>> [x for row in zip([1], [2, 3]) for x in row]
[1, 2]
>>> [x for row in zip([], [1, 2, 3]) for x in row]
[]
>>> [x for row in zip([4, 5, 6, 7], [1]) for x in row]
[4, 1]
如果您想从最长的列表中获取每个元素,可以使用itertools.zip_longest
:
>>> from itertools import zip_longest
>>> [x for row in zip_longest([4, 5, 6, 7], [1]) for x in row]
[4, 1, 5, None, 6, None, 7, None]
它将None
元素添加到最短列表中。
答案 2 :(得分:2)
此功能适用于上述及以外的这些案例!
def joo(l1,l2):
l = []
for i in range(min(len(l1), len(l2))):
l.append(l1[i])
l.append(l2[i])
return l
l = joo(l1, l2)
感谢Adirio的建议!
答案 3 :(得分:1)
您可以使用zip:
def zip_lists(list1, list2):
return [a for b in zip(list1, list2) for a in b]
print(zip_lists([1, 2, 3], [1, 2, 3])) # => [1, 1, 2, 2, 3, 3]
print(zip_lists([1], [2, 3])) # => [1, 2]
print(zip_lists([], [1, 2, 3])) # => []
print(zip_lists([4, 5, 6, 7], [1])) # => [4, 1]