一次向列表中的两个元素添加元素

时间:2017-04-11 11:12:04

标签: python list append

不太清楚如何构建它,但我试图将一个元素从一个列表添加到另一个列表。

x = [1,1,2,2,3,3]

a=[['b'],['c'],['d'],['e'],['f'],['g'],['h'],['i'],['j'],['k'],['l'],['m']]

我正在尝试获得这样的输出,其中添加了一个元素:

a=[['b',1],['c',1],['d',2],['e',2],['f',3],['g',3],['h',1],['i',1],['j',2],['k',2],['l',3],['m',3]]

2 个答案:

答案 0 :(得分:4)

如果您想修改列表,可以使用for循环并使用itertools.cycle

from itertools import cycle

for ai,xi in zip(a,cycle(x)):
    ai.append(xi)

给出:

>>> a
[['b', 1], ['c', 1], ['d', 2], ['e', 2], ['f', 3], ['g', 3], ['h', 1], ['i', 1], ['j', 2], ['k', 2], ['l', 3], ['m', 3]]

如果您不关心原始列表,还可以使用列表理解构建新列表列表

a[:] = [ai+[xi] for ai,xi in zip(a,cycle(x))]

给出:

>>> [ai+[xi] for ai,xi in zip(a,cycle(x))]
[['b', 1], ['c', 1], ['d', 2], ['e', 2], ['f', 3], ['g', 3], ['h', 1], ['i', 1], ['j', 2], ['k', 2], ['l', 3], ['m', 3]]

答案 1 :(得分:4)

这可以通过使用mod运算符在本机Python中完成:

x = [1,1,2,2,3,3]
a=[['b'],['c'],['d'],['e'],['f'],['g'],['h'],['i'],['j'],['k'],['l'],['m']]
results = [[value[0], x[index % len(x)]] for index, value in enumerate(a)]
print(results)