2014-07-23 31 views
0

我试图通过字典,尤其是当值的长度不等时(这对我造成最大的错误)得到一个迭代的牢固把握。我实际上正在为我的篮球程序运行一个脚本来寻找对。这里是球队的一个片段:在字典中创建对的唯一值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')] 

所以苏茜和Bryan的价值观没有任何共同之处。其他两个也一样。非常有兴趣看到解决问题的方法。

+0

到目前为止您尝试了哪些方法? –

+0

“值不等长”与遍历字典毫无关系。在字典中,每个值都只是一个值;事实上,它恰好是一个列表或字符串或任何长度不影响任何东西。 – abarnert

回答

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

可能是我会怎么做?

1

这仅仅是一个循环的物质循环中的:

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

最后一行中有一个隐含的循环中,当然(实际上,两个,因为列表中的“进入”本身有一个循环,但让我们忘了那个,因为它只是一个小问题,而不是概念问题)。

如果你想在第三循环明确:

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转换为一个集合来加快速度,但可能没有必要考虑列表的长度有多短。

最后,如果您了解生成器,则“添加对”仅表示pairs.append((player, other))yield (player, other)

希望这足以让你自己写。

+0

+1实际帮助他学习(像往常一样:P) –