我是编程和结识Python的新手。
我正在尝试组合2个数组,假设它是x=['a','b','c']
和y=['1','2','3','4']
。我如何获得combined=['a1','b2','c3','a4']
?
预先感谢
答案 0 :(得分:4)
使用itertools.cycle()
+ zip()
:
>>> from itertools import cycle
>>> x = ['a','b','c']
>>> y = ['1','2','3','4']
>>> [a + b for a, b in zip(cycle(x), y)]
['a1', 'b2', 'c3', 'a4']
@SanV的注释中指出,要处理不同大小的列表,可以使用以下功能:
def zip_lists(x, y):
if len(x) > len(y):
y = cycle(y)
elif len(x) < len(y):
x = cycle(x)
return [a + b for a, b in zip(x, y)]
这是这样的:
>>> zip_lists(['a','b','c'], ['1','2','3','4'])
['a1', 'b2', 'c3', 'a4']
>>> zip_lists(['a','b','c', 'd', 'e'], ['1','2','3','4'])
['a1', 'b2', 'c3', 'd4', 'e1']
>>> zip_lists(['a','b','c', 'd'], ['1','2','3','4'])
['a1', 'b2', 'c3', 'd4']