pythonic迭代set / remnant集

时间:2016-04-03 17:03:23

标签: python

执行以下操作的简洁方法是什么:

def foo(aSet) :
    for a in aSet:
        for remaining in aSet - {a} :
            doSomething(a,remaining)

我在想一定有一些方法可以把它写成一个for循环?

2 个答案:

答案 0 :(得分:3)

aSet = {1,2,3}
[[i,j] for i in aSet for j in aSet if j != i]
#=> [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

在您的情况下,您需要一个发电机

(doSomething(i, j) for i in aSet for j in aSet if j != i)

答案 1 :(得分:3)

>>> from itertools import permutations
>>> aSet = {1, 2, 3}
>>> list(permutations(aSet, 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

>>> for a, remaining in permutations(aSet, 2):
...     print(a, remaining, end=', ')
... 
1 2, 1 3, 2 1, 2 3, 3 1, 3 2,