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

2024-05-02 22:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一个数组:

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

我想把数组排序成这样:

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

我该怎么做?你知道吗


Tags: 排序数组liamerinnamescorerorynamesscore
3条回答
namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2"]
namesscore = [tuple(el.split()) for el in namesscore]
temp = dict((el[1], el[0]) for el in namesscore)

merge = {}
for key, value in temp.iteritems():
    if value not in merge:
        merge[value] = [key]
    else:
        merge[value].append(key)

print [' '.join((k, ' '.join(v))) for k, v in merge.iteritems()]

>>> ['Rory: 1 4', 'Liam: 2 5 6', 'Erin: 8']
from collections import defaultdict
import operator

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

# Build a dictionary where the key is the name and the value is a list of scores
scores = defaultdict(list)
for ns in namesscore:
    name, score = ns.split(':')
    scores[name].append(score)

# Sort each persons scores
scores = {n: sorted(s) for n, s in scores.items()}   

# Sort people by their scores returning a list of tuples
scores = sorted(scores.items(), key=operator.itemgetter(1))   

# Output the final strings
scores = ['{}: {}'.format(n, ', '.join(s)) for n, s in scores]

print scores

> ['Rory:  1,  4', 'Liam:  2,  5,  6', 'Erin:  8']

我会迭代这个列表,并为每个项目在名称和分数之间进行拆分。然后我会创建一个dict(更准确地说,是一个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()]

相关问题 更多 >