我很难理解如何组合列表中的元素。
我有:
a = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
我想通过从每个列表成员中获取元素来创建三元组 但总是包括第一个元素。这段代码完成了一半 作业:
r=[[]]
for x in a[0:3]:
t = []
for y in x:
for i in r:
t.append(i+[y])
r = t
[R
[[1, 3, 6], [2, 3, 6], [1, 4, 6], [2, 4, 6], [1, 5, 6], [2, 5, 6]]
但我也想要:
[[1,6,7], [1,6,8], [1,6,9] etc.]
有人可以建议一个好的方法吗?
答案 0 :(得分:2)
使用itertools
:
import itertools
a = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
for xss in itertools.combinations(a, 3): # pick 3 lists.
# xss => ([1, 2], [3, 4, 5], [6])
# ([1, 2], [3, 4, 5], [7, 8, 9, 10])
# ...
indexed = [enumerate(x) for x in xss]
# indexed => [[(0, 1), (1, 2)], [(0, 3), (1, 4), (2, 5)], [(0, 6)]]
# ^^^^^^^^^^^^^^^^ list(enumerate([1, 2]))
for xs in itertools.product(*indexed):
# xs => ((0, 1), (0, 3), (0, 6))
# ((0, 1), (0, 3), (0, 7))
# ((0, 1), (0, 6), (0, 7))
# ...
if all(i > 0 for i, x in xs): # exclude no first item is selected.
continue
print [x for i, x in xs]
更新对评论的回复。
import itertools
a = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
for xss in itertools.combinations(a[1:], 2):
xss = (a[0],) + xss
indexed = [enumerate(x) for x in xss]
for xs in itertools.product(*indexed):
if all(i > 0 for i, x in xs):
continue
print [x for i, x in xs]
输出:
[1, 3, 6]
[1, 4, 6]
[1, 5, 6]
[2, 3, 6]
[2, 4, 6]
[2, 5, 6]
[1, 3, 7]
[1, 3, 8]
[1, 3, 9]
[1, 3, 10]
[1, 4, 7]
[1, 4, 8]
[1, 4, 9]
[1, 4, 10]
[1, 5, 7]
[1, 5, 8]
[1, 5, 9]
[1, 5, 10]
[2, 3, 7]
[2, 3, 8]
[2, 3, 9]
[2, 3, 10]
[2, 4, 7]
[2, 5, 7]
[1, 6, 7]
[1, 6, 8]
[1, 6, 9]
[1, 6, 10]
[2, 6, 7]
[2, 6, 8]
[2, 6, 9]
[2, 6, 10]