简体   繁体   中英

creating pairs from unique values in a dictionary python

i'm trying to get a firm grasp of iterating through dictionaries, especially when values are of unequal lengths (this is causing the most errors for me). I'm actually trying to run a script for my basketball program to find pairs. here is a snippet of the team:

team = {'Bryan': ['m', 'pg','sg','sf'], 'Steve': ['m', 'pg','sf','c'], 'Suzy': ['f,','c','pf'], 'Jen': ['f','pf']}

basically, i set up my dictionaries so that if no key has any values in common within the list, they are a pair.

the output that i've been trying to get is:

[('Suzy','Bryan'), ('Jen','Bryan'), ('Jen','Steve')]

so Suzy and Bryan's values within the list have nothing in common. same for the other two. very interested to see ways to approach the problem.

import itertools
def find_matches(team):
   for player1,player2 in itertools.combinations(team.keys(),2):
       if not set(team[player1]).intersection(team[player2]):
           yield (player1,player2)

team = {'Bryan': ['m', 'pg','sg','sf'], 'Steve': ['m', 'pg','sf','c'], 'Suzy': ['f,','c','pf'], 'Jen': ['f','pf']}           
print list(find_matches(team))

is probably how I would do it ...

This is really just a matter of loops inside loops:

for each player
    for each other player
        if no value in player's values is in other player's values, add the pair

That last line has an implicit loop in it, of course (actually, two, because "is in" on a list itself has a loop in it, but let's forget that one, as it's just a minor performance issue, not a conceptual issue).

If you want to make the third loop explicit:

for each player
    for each other player
        for each value in player's values
            if value in other player's values, break
        else add the pair

So, how do you translate that to Python?

Well, "for each player" is just for player in team —or for player, values in team.items() may save you a bit of work later.

Then "for each other player" is the same thing again. (Of course that means that "player" can come up as an "other player" to compare to, which is unnecessary—but it doesn't hurt anything, except a minor performance cost comparing someone to himself, which will fail on the first check.)

Then "if no value in player's values is in other player's values" is just if not any(value in other_values for value in player_values) . You can make this faster by converting the other_values to a set, but there's probably no need for that given how short your lists are.

Finally, "add the pair" just means pairs.append((player, other)) , or yield (player, other) if you understand generators.

Hopefully that's enough to write it yourself.

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