gpt4 book ai didi

python - 对数组中的特定值进行分组

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:57 24 4
gpt4 key购买 nike

假设我有一个像这样的数组:

namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2",]

我想对该数组进行排序,使其像这样:

namescore = ["Rory: 1, 4", "Liam: 5, 6, 2", "Erin: 8"]

我该怎么做?

最佳答案

我会迭代列表,并为每个项目将其拆分为名称和分数。然后,我创建一个字典(更准确地说:一个 OrderedDict,以保留顺序)并累积每个名称的分数。迭代完成后,可以将其转换为所需格式的字符串列表:

from collections import OrderedDict

def group_scores(namesscore):
mapped = OrderedDict()
for elem in namesscore:
name, score = elem.split(': ')
if name not in mapped:
mapped[name] = []
mapped[name].append(score)

return ['%s%s%s' % (key, ': ', ', '.join(value)) for \
key, value in mapped.items()]

关于python - 对数组中的特定值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056547/

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