从python字典中的唯一值创建对

2024-04-16 09:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力牢牢掌握遍历字典的方法,尤其是当值的长度不等时(这对我来说是造成最多错误的原因)。我其实是在试着为我的篮球项目做一个脚本来寻找搭档。以下是团队的一个片段:

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

基本上,我设置了字典,这样如果列表中没有键有共同的值,它们就是一对

我一直想得到的结果是:

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

所以苏西和布莱恩在名单中的价值观没有共同点。其他两个也一样。很想看看解决问题的方法


Tags: 项目方法脚本字典错误原因sfbryan
2条回答
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))

也许我会这么做

这实际上只是循环中的循环:

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

最后一行中当然有一个隐式循环(实际上,有两个,因为列表中的“is in”本身也有一个循环,但我们还是忘了这一个,因为它只是一个次要的性能问题,而不是概念问题)

如果要使第三个循环显式化:

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

那么,如何将其转换为Python呢

好吧,“对于每个玩家”只是for player in team——或者for player, values in team.items()可能会为您以后节省一些工作

那么“为对方球员”又是一回事了(当然,这意味着“玩家”可以作为一个“其他玩家”来比较,这是不必要的,但它不会损害任何东西,除了一个小的性能成本比较某人和他自己,这将失败的第一次检查。)

那么“如果玩家的价值观中没有价值观是其他玩家的价值观”就是if not any(value in other_values for value in player_values)。您可以通过将other_values转换为一个集合来加快这个过程,但是考虑到列表有多短,可能没有必要这样做

最后,“add the pair”只是指pairs.append((player, other)),或者yield (player, other),如果您理解生成器的话

希望这足够你自己写了

相关问题 更多 >