如何从python列表中获取元素的组合?

use*_*366 1 python

我有一个清单L = [1,2,3].从列表和输出中获取2个元素的所有可能独特组合的最佳方法是以迭代的方式进行:

第1次迭代= 1次,第2次迭代= 1次,第3次迭数= 2次3次

谢谢

the*_*eye 5

最好的方法是使用itertools.combinations,像这样

from itertools import combinations
print [item for item in combinations(L, r = 2)]
# [(1, 2), (1, 3), (2, 3)]
Run Code Online (Sandbox Code Playgroud)

你可以这样迭代

for item in combinations(L, r = 2):
    print item
# (1, 2)
# (1, 3)
# (2, 3)
Run Code Online (Sandbox Code Playgroud)

或者您可以访问这样的单个元素

for item in combinations(L, r = 2):
    print item[0], item[1]
Run Code Online (Sandbox Code Playgroud)