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']
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()]
我会迭代这个列表,并为每个项目在名称和分数之间进行拆分。然后我会创建一个dict(更准确地说,是一个
OrderedDict
,以保持顺序)并累积每个名字的分数。迭代完成后,可以将其转换为所需格式的字符串列表:相关问题 更多 >
编程相关推荐