Reputation: 4027
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?
Upvotes: 3
Views: 73
Reputation: 5616
>>> 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,
Upvotes: 3
Reputation: 83680
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)
Upvotes: 3