簡體   English   中英

Python 列表列表合並/刪除重復項

[英]Python List of Lists Merging/removing duplicates

我有一個具有不同屬性的列表列表:

list = [['jake', '100', 'science'], ['sam', '200', 'math'], ['jake', '100', 'science'], ['sam', '200', 'science']]

該列表分別代表學生的姓名、考試成績和科目。

這是所需的 output: list = [['jake', '200', 'science'], ['sam', '200', 'math'], ['sam', '200', 'science']]

Jake 的兩個科學分數的分數相加 (100+100 = 200) 並刪除了重復的列表。

我想添加屬於同一個人和同一科目的考試成績,並將其他成績分開。 知道如何無縫地做到這一點嗎?

您可以使用itertools中的groupby來很好地解決這個問題。

您需要使用鍵lambda x: (x[0], x[2])進行排序和分組,以確保排序和分組由學生和科目完成。

from itertools import groupby
list = [
    ['jake', '100', 'science'],
    ['sam', '200', 'math'],
    ['jake', '100', 'science'],
    ['sam', '200', 'science']
]

sorted_list = sorted(list, key=lambda x: (x[0], x[2]))
grouped_list = groupby(sorted_list, key=lambda x: (x[0], x[2]))

output_list = [[student, str(sum(int(score[1]) for score in scores)), subject]
    for (student, subject), scores in grouped_list]

根據需要提供:

[['jake', '200', 'science'], ['sam', '200', 'math'], ['sam', '200', 'science']]

類似的東西

from functools import reduce

list = [['jake', '100', 'science'], ['sam', '200', 'math'], ['jake', '100', 'science'], ['sam', '200', 'science']]


def reducer(acc, item):
    key = f'{item[0]}_{item[2]}'
    if key not in acc:
        item[1] = int(item[1])
        acc[key] = item
    else:
        acc[key][1] = acc[key][1] + int(item[1])

    return acc

new_list = reduce(reducer, list, {}).values()


print(new_list)

暫無
暫無

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

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