gpt4 book ai didi

Python - 二维列表 - 在一列中查找重复项并在另一列中求和值

转载 作者:行者123 更新时间:2023-12-05 01:55:43 26 4
gpt4 key购买 nike

我有一个二维列表,其中分别包含足球运动员的姓名、他们进球的次数以及他们尝试射门的次数。

player_stats = [['亚当', 5, 10], ['凯尔', 12, 18], ['乔', 20, 35], ['亚当', 15, 20], [ '查理', 31, 58], ['乔', 6, 14], ['亚当', 10, 15]]

从这个列表中,我试图返回另一个列表,该列表仅显示每个玩家的一个实例及其各自的目标和目标尝试,就像这样:

player_stats_totals = [['亚当', 30, 45], ['凯尔', 12, 18], ['乔', 26, 49], ['查理', 31, 58]]

在 Stack Overflow 上搜索后,我了解到(来自 this thread)如何返回重复玩家的索引

x = [player_stats[i][0] for i in range (len(player_stats))]

for i in range (len(x)):
if (x[i] in x[:i]) or (x[i] in x[i+1:]): print (x[i], i)

但在之后如何进行以及是否确实此方法与我的需要严格相关(?)上陷入困境

返回所需总计列表的最有效方法是什么?

最佳答案

使用字典来累积给定玩家的值:

player_stats = [['Adam', 5, 10], ['Kyle', 12, 18], ['Jo', 20, 35], ['Adam', 15, 20], ['Charlie', 31, 58], ['Jo', 6, 14], ['Adam', 10, 15]]

lookup = {}
for player, first, second in player_stats:

# if the player has not been seen add a new list with 0, 0
if player not in lookup:
lookup[player] = [0, 0]

# get the accumulated total so far
first_total, second_total = lookup[player]

# add the current values to the accumulated total, and update the values
lookup[player] = [first_total + first, second_total + second]

# create the output in the expected format
res = [[player, first, second] for player, (first, second) in lookup.items()]
print(res)

输出

[['Adam', 30, 45], ['Kyle', 12, 18], ['Jo', 26, 49], ['Charlie', 31, 58]]

一个更高级的 pythonic 版本是使用 collections.defaultdict :

from collections import defaultdict

player_stats = [['Adam', 5, 10], ['Kyle', 12, 18], ['Jo', 20, 35],
['Adam', 15, 20], ['Charlie', 31, 58], ['Jo', 6, 14], ['Adam', 10, 15]]

lookup = defaultdict(lambda: [0, 0])
for player, first, second in player_stats:
# get the accumulated total so far
first_total, second_total = lookup[player]

# add the current values to the accumulated total, and update the values
lookup[player] = [first_total + first, second_total + second]

# create the output in the expected format
res = [[player, first, second] for player, (first, second) in lookup.items()]

print(res)

这种方法的优点是跳过初始化。两种方法都是 O(n)。

注意事项

表达式:

res = [[player, first, second] for player, (first, second) in lookup.items()]

是一个list comprehension ,相当于下面的 for 循环:

res = []
for player, (first, second) in lookup.items():
res.append([player, first, second])

此外,请阅读 this用于理解解包。

关于Python - 二维列表 - 在一列中查找重复项并在另一列中求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70118390/

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