【发布时间】:2013-11-29 10:43:59
【问题描述】:
list = [1,2,3,4]
我想得到下面的结果并将它们存储在 csv 文件中。 (共 6 行)
1,2
1,3
1,4
2,3
2,4
3,4
这有什么功能,或者我怎样才能完成并将其存储在 csv 文件中?
【问题讨论】:
list = [1,2,3,4]
我想得到下面的结果并将它们存储在 csv 文件中。 (共 6 行)
1,2
1,3
1,4
2,3
2,4
3,4
这有什么功能,或者我怎样才能完成并将其存储在 csv 文件中?
【问题讨论】:
itertools是你的朋友...
http://docs.python.org/2/library/itertools.html
>>> import itertools
>>> x = [1, 2, 3, 4]
>>> list(itertools.combinations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
【讨论】:
'\n'.join(','.join(map(str, v)) for v in itertools.combinations(x, 2)) 获得所需的输出。
使用itertools.combinations。它内置在 Python 2.6+ 中。
import itertools
pairs = itertools.combinations(list, 2)
【讨论】:
一种选择是使用itertools.permutations 和列表理解:
>>> [(x, y) for x, y in itertools.permutations(mylist, 2) if x < y]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
条件x < y 确保您只获得x 低于y 的排列。
更好的选择是使用itertools.combinations(mylist, 2)。
【讨论】:
combinations呢?
product 建立combinations,然后再用combinations 建立permutations。 :)
这很简单,你可以自己做:
l=[1,2,3,4]
for i in range(0,len(l)):
for j in range (i+1,len(l)):
print l[i],l[j]
但是使用itertools 的解决方案可以更容易泛化。
【讨论】: