简体   繁体   中英

pythonic way to iterate over a set/remnant set

what is a clean way of doing the following:

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

I am thinking there must be some way of writing that as just one for loop?

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]]

In your case you need a generator

(doSomething(i, j) for i in aSet for j in aSet if j != i)
>>> 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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM