是否有更多pythonic方式来编写此代码。我试图在不同的不同集合中找到2个元素的所有组合,但排除同一集合中成员之间的组合。因此,如果0和1在同一组中,我不想要组合01。
我更喜欢这样做的模块。我看了https://docs.python.org/2/library/itertools.html 但这需要输入单个列表,并给出其元素的组合。我想输入多套。
我想我可以使用itertools.combinations生成所有组合,然后在同一组中减去那些但这看起来很浪费。还有更好的方法吗?
setA = [0,1,4]
setB = [2,3]
边包含(['02','03','13','12','42','43'])
setC = [0,2]
setD = [1]
setE = [3]
edge包含set ['32','31','01','21','30']
edge= set()
edges= set()
setA = set([0, 1, 4])
setB = set([2, 3])
setC = set([0,2])
setD = set([1])
setE = set([3])
print "Two set combinations of elements (not between elements in same set)"
for i in setA:
for j in setB:
if str(i)+str(j) in edge:
pass
edge.add( str(i)+str(j) )
print edge
print "Three set combinations of elements (not between elements in same set)"
for i in setC:
for j in setD:
if str(i)+str(j) in edges:
pass
edges.add( str(i)+str(j) )
for k in setE:
if str(k)+str(i) in edges:
pass
edges.add( str(k)+str(i) )
if str(k)+str(j) in edges:
pass
edges.add( str(k)+str(j) )
print edges
答案 0 :(得分:1)
这个itertools单线程怎么样?
C = [0,2]
D = [1]
E = [3]
import itertools as it
print [list(it.product(x, y)) for x, y in it.combinations([C, D, E], 2)]