Python 一个接一个地合并两个列表

Python 一个接一个地合并两个列表,python,Python,我正在尝试合并列表以产生如下结果: [a,1,b,2,c,3]但我不能让它工作。你能告诉我怎么了/告诉我怎么做吗 def newList(a, b): tmp = [] tmp.append(zip(a, b)) return tmp a = ['a', 'b', 'c'] b = [1, 2, 3] print(newList(a, b)) 因此,我只在0x0449FE18处获得zip对象。您需要展平由zip生成的序列。最简单的方法是使用itertools.cha

我正在尝试合并列表以产生如下结果: [a,1,b,2,c,3]但我不能让它工作。你能告诉我怎么了/告诉我怎么做吗

def newList(a, b):
    tmp = []
    tmp.append(zip(a, b))
    return tmp

a = ['a', 'b', 'c']
b = [1, 2, 3]

print(newList(a, b))

因此,我只在0x0449FE18处获得zip对象。

您需要展平由
zip
生成的序列。最简单的方法是使用
itertools.chain.from\u iterable

>>> from itertools import chain
>>> list(chain.from_iterable(zip(['a', 'b', 'c'], [1,2,3])))
['a', 1, 'b', 2, 'c', 3]
类方法
from_iterable
获取像
[('a',1),('b',2),…]
这样的iterable,并通过从子iterable中从左到右一次提取一个元素,将其转换为单个iterable。

无需导入

b=[1,2]

a=['a','b','c']

result = [item for a in map(None, a, b) for item in a][:-1]
[a',1',b',2',c']

重要数组“b”比数组“a”少一个元素

如果长度相同

result = [item for a in map(None, a, b) for item in a]

[a',1',b',2',c',3]

您不需要使用
邮政编码。假设两个列表具有相同数量的元素(如您的问题所示),您可以执行以下操作

>>> [x for y in zip(['a', 'b', 'c'],[1, 2, 3]) for x in y]
['a', 1, 'b', 2, 'c', 3]
newList = list()
for i in range(len(a)):
    newList.append(a[i])
    newList.append(b[i])
print(newList)
newList = list()
biggestList = len(a) if len(a) > len(b) else len(b)
for i in range(biggestList):
    if a[i]:
        newList.append(a[i])
    if b[i]:
        newList.append(b[i])
print(newList)
如果列表大小不一样,那么您需要问自己一些有关订购的问题,但您可以尽可能简单地完成

newList = list()
for i in range(len(a)):
    newList.append(a[i])
    newList.append(b[i])
print(newList)
newList = list()
biggestList = len(a) if len(a) > len(b) else len(b)
for i in range(biggestList):
    if a[i]:
        newList.append(a[i])
    if b[i]:
        newList.append(b[i])
print(newList)

您可以根据列表大小的标准以及如何处理顺序来处理此逻辑

最后需要将其转换为列表。
import操作符;打印列表(reduce(operator.concat,zip(a,b)))