簡體   English   中英

有沒有辦法枚舉共享相同索引的列表或詞典?

[英]Is there a way to enumerate a list or dictionary that share the same index?

我想枚舉列表或字典,如果項目共享相同的值或相等,則我希望它們使用1索引。

這是我的代碼:

def print_data(league_results):
    for i, (team, points) in 
    enumerate(sorted(league_results.items(), key=lambda x: x[1], 
    reverse=True), 1):
        if points == 1:
          i = i
        print('{}. {}, {}'.format(i, team.strip(''), points))

輸出量

1. Man City, 6
2. Liverpool, 5
3. Everton, 1
4. Stoke, 1
5. Fulham, 0

這是我想要的輸出:如果一個團隊分享一個分數,他們應該具有相同的索引。 Everton&Stoke必須共享相同的索引。

1. Man City, 6
2. Liverpool, 5
3. Everton, 1 
3. Stoke, 1
4. Fulham, 0

您可以使用itertools.groupby

def print_data(league_results):
    grouped_results = itertools.groupby(
        sorted(league_results.items(), key=lambda x: x[1], reverse=True), 
        key=lambda x: x[1]
    )
    for i, (_, teams) in enumerate(grouped_results, 1):
        for team, points in teams:
            print('{}. {}, {}'.format(i, team.strip(''), points))

結果:

1. Man City, 6
2. Liverpool, 5
3. Everton, 1
3. Stoke, 1
4. Fulham, 0

這里有現場示例

說明:

groupby將使點數與團隊之間的匹配變得可迭代(如果對它們進行排序將對其進行分組),從而為我們提供(points, [(team, points), ...]), ...的可迭代性。 因此,在枚舉它時,您將枚舉這些組,這將成為我們的索引i 因為我們希望枚舉從1而不是0開始,所以我們只是簡單地要求函數從它開始enumerate(iterable, start_enumerate_value)

暫無
暫無

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

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