簡體   English   中英

從字典python中的唯一值創建對

[英]creating pairs from unique values in a dictionary 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')]

因此列表中Suzy和Bryan的值沒有共同之處。 其他兩個相同。 非常有興趣了解解決問題的方法。

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

最后一行當然有一個隱式循環(實際上是兩個,因為列表中的“位於”本身也有一個循環,但我們忘了一個,因為它只是一個較小的性能問題,而不是概念問題) )。

如果要使第三個循環更明確:

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()或者for player, values in team.items()可能會for player, values in team.items()您節省一些工作。

那么“對於其他玩家”又是同一回事。 (當然,這意味着“玩家”可以作為“其他玩家”來比較,這是不必要的,但它並不會對任何人造成傷害,除了與某人進行比較而產生的較小的性能成本外,這首先會失敗)校驗。)

那么,“如果玩家的值中if not any(value in other_values for value in player_values)值是其他玩家的值中”,就if not any(value in other_values for value in player_values) 您可以通過將other_values轉換為集合來使其更快,但是考慮到列表的長度,可能不需other_values

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

希望這足以自己編寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM