gpt4 book ai didi

python - 对 python 列表中的相关值求和

转载 作者:太空宇宙 更新时间:2023-11-03 13:56:31 25 4
gpt4 key购买 nike

这是从记录中打印的值,我需要根据第二个数字对第一个数字求和。如果第一个第二个数字相同,则需要添加第一个数字。

record = [[2, 3], [3, 3], [5, 4], [1, 4]]

Expected output = [5, 3], [6, 4]]

最佳答案

您应该先排序,然后 itertools.groupby 第二个值。

import itertools
import operator

records = [[2, 3], [3, 3], [5, 4], [1, 4]]
records.sort(key=operator.itemgetter(1))
groups = itertools.groupby(records, key=operator.itemgetter(1))
# groups is now a generator that produces the values:
# (3, [[2, 3], [3, 3]])
# (4, [[5, 4], [1, 4]])

然后生成一个结果列表:

result = [[sum(record[0] for record in records), grpname] for grpname, records in groups]

关于python - 对 python 列表中的相关值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com