gpt4 book ai didi

python - 识别数组中的相似实例并合并它们

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:57 25 4
gpt4 key购买 nike

我有一个数组数组,像这样......

[['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Summer Smith', 4], ['Summer Smith', 4], ['Summer Smith', 4], ['Abradolf Lincler', 4], ['Summer Smith', 4], ['Summer Smith', 4]]

我希望能够扫描每个数组,如果元素 0 已经存在于数组中,则合并它们并将第一个元素加在一起。例如,有 5 个 Summer Smith 实例。代码应该识别出它是同一名球员,因此将所有 Summer Smith 得分相加,使 Summer Smith 总得分为 20。它应该为每个球员这样做。所以这一切看起来像,例如,

[['Harry',20], ['Jake', 16]]....

我试着...

for array in arrays:
if array[0] in [not sure what to do now]

最佳答案

考虑使用 dictionary跟踪每个玩家的得分总和:

scores = [['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Summer Smith', 4], ['Summer Smith', 4], ['Summer Smith', 4], ['Abradolf Lincler', 4], ['Summer Smith', 4], ['Summer Smith', 4]]

grouped_scores = {}
for name, score in scores:
if name not in grouped_scores: grouped_scores[name] = score
else: grouped_scores[name] += score

然后您可以将结果作为列表的列表取回:

merged_scores = [list(t) for t in grouped_scores.items()]
print(merged_scores)
# [['Summer Smith', 20], ['Scary Terry', 20], ['Abradolf Lincler', 32]]

关于python - 识别数组中的相似实例并合并它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291206/

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