Python自动提取列表索引并附加数据

时间:2018-03-14 22:20:17

标签: python list loops append combinations

我不知道如何描述问题。举个例子:

a=[[1,2],[3,4],[5,6]]
b=[['a','b'],['c','c']]
x=[a,b]

现在我想将x元素的元素追加到它们之前的元素(在这种情况下是每个元素上的b个元素),我可以使用

t=[]
for i in a:
    for j in b:
        t.append(i+j)
然后我想要的结果变成了:

t
[[1, 2, 'a', 'b'],
 [1, 2, 'c', 'c'],
 [3, 4, 'a', 'b'],
 [3, 4, 'c', 'c'],
 [5, 6, 'a', 'b'],
 [5, 6, 'c', 'c']]

在这种情况下,我知道x中有ab,所以我可以追加它们。但是,如果我不知道x中有多少项,我怎么能追加这些元素?

喜欢x=[a,b,c,d,e,...]

尝试过循环,但似乎不太好。我在想combination但不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

生成成对产品并使用itertools'productchain函数(分别)展平它们:

from itertools import chain, product    
t = [list(chain.from_iterable(i)) for i in product(a, b)]

print(t)
[[1, 2, 'a', 'b'],
 [1, 2, 'c', 'c'],
 [3, 4, 'a', 'b'],
 [3, 4, 'c', 'c'],
 [5, 6, 'a', 'b'],
 [5, 6, 'c', 'c']]

此解决方案将推广到任意数量的列表:

x = [a, b, c, ...]
t = [list(chain.from_iterable(i)) for i in product(*x)]