簡體   English   中英

Python:字典打印值而不是鍵

[英]Python: Dictionary printing value instead of key

這是我的代碼:
如果有應該做的線:比較的第一個 Dict1Dict2 ,然后將打印的字典是否在它的第一個地方較小的第一個 ,然后它會刪除該字典第一個鍵和值 請注意啟動時的while循環。

它的作用是
1.打印值,而不是鍵。 2.它打印的時間減少了1分鍾,而不是應有的打印時間,即,如果dict 1有2個鍵,而dict2有3個鍵,它將輸出5行,但僅輸出4行。Dict1 = {“ Player1”可以幫助您自己: 46,“ Player2”:34} Dict2 = {“ Player3”:38,“ Player4”:55}並且它應該輸出* keys ** Player2然后是Player3然后是Player1然后是Player4,每個都在自己的行中,

 while Dict1 and Dict2:

     if Dict1.get(list(Dict1.keys())[0]) > Dict2.get(list(Dict2.keys())[0]):
         print(Dict2[list(Dict2.keys())[0]])
         del Dict2[list(Dict2.keys())[0]]
     elif Dict1.get(list(Dict1.keys())[0]) < Dict2.get(list(Dict2.keys())[0]):
         print(Dict1[list(Dict1.keys())[0]])
         del Dict1[list(Dict1.keys())[0]]

編輯:我從用戶/馬克·泰勒那里得到了幫助。 他告訴我這段代碼:

for (key1, val1), (key2, val2) in zip(Dict1.items(), Dict2.items()):
    if val1 > val2:
      print(key2)
    elif val1 < val2:
      print(key1)

但是只輸出一次,它應該輸出Dict1和Dict2中的每個鍵。我必須做的是:這是關於足球的。 Dict1的鍵是得分者的名字,其值在他們得分的那一刻。 全部一支團隊。 Dict2對於另一個團隊來說是相同的。 我已經按其值對Dict1和Dict2進行了排序。 我需要輸出他們在比賽中得分的球員(第一線得分第一,第二線得分第二的球員,等等)

下面的代碼如何將to dicts合並為元組的已排序列表。

team1 = {"Player1": 46, "Player2": 34}
team2 = {"Player9": 89, "Player3": 38, "Player4": 55}

both_teams = [(k, v) for k, v in team1.items()]
both_teams.extend([(k, v) for k, v in team2.items()])
sorted_both_teams = sorted(both_teams, key=lambda x: x[1])
for entry in sorted_both_teams:
    print('Player {} scored at {}'.format(entry[0], entry[1]))

輸出量

Player Player2 scored at 34
Player Player3 scored at 38
Player Player1 scored at 46
Player Player4 scored at 55
Player Player9 scored at 89

暫無
暫無

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

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