简体   繁体   中英

How to iterate over each pair of items in a dictionary

I'm making a gravity simulator and I need to calculate the resultant force acting upon each body.

In order to do this, I need to iterate through every pair of bodies in a dictionary (id: instance of Body class) and get the gravitational force between those two bodies. Then, I would add up all the forces and get the resultants.

But, how do I iterate over each pair of items in a dictionary only once in Python? If the celestial bodies were kept in a list, it would be simple:

for i in range(len(bodies)):
    for j in range(len(bodies) - i - 1):
        k = j - i + 1
        b1 = bodies[i]
        b2 = bodies[k]

values() and itertools ' combinations are ideal for this use case.

from itertools import combinations
for a, b in combinations(bodies.values(), 2):
    print a, b

you're looking for itertools.combinations() :

An example:

In [76]: lis=['a','b','c','d']  #consider these as your dictionary items

In [77]: [x for x in combinations(lis,2)]
Out[77]: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

The itertools module provides an excellent combinations method you could use:

from itertools import combinations

bodies = {}
# add bodies

for a,b in combinations(bodies.values(), 2):
    # a and b are a pair of bodies. do stuff
    pass

Incidentally, this will still work even if you use a list:

from itertools import combinations

bodies = []
# add bodies

for a,b in combinations(bodies, 2):
    pass

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