从数组中分组特定值

时间:2015-10-10 16:57:26

标签: python arrays python-3.x

说我有一个这样的数组:

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

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

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

我该怎么做?

4 个答案:

答案 0 :(得分:1)

我会迭代列表,并且每个项目都会在名称和分数之间进行分割。然后我会创建一个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()]

答案 1 :(得分:0)

toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);

答案 2 :(得分:0)

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

od = {}

[ od.setdefault(a,[]).append(b) for a,b in map(lambda x : (x[0:x.find(':')],x[-1]), namesscore)]

namesscore = ['  '.join((k,' '.join(sorted(v))))  for k, v in od.items()]

print(namesscore)

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

答案 3 :(得分:0)

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']