Python 对数组中的特定值进行分组
假设我有这样一个数组:Python 对数组中的特定值进行分组,python,arrays,python-3.x,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"] 我该怎么做呢?我会迭代列表,并为每个项目在名称和分数之间进行分割。然后我会创建一个dict(更准确地说:一个OrderedDict,以保持顺序),并为每个名字累积分
namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2",]
我想对数组进行排序,使其如下所示:
namescore = ["Rory: 1, 4", "Liam: 5, 6, 2", "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()]
似乎您需要一个使用名称作为键的字典,并为它们分配一个可以在其上使用附加的列表值。根据什么标准对最终数组进行排序?这将返回“AttributeError:“OrderedDict”对象没有属性“iteritems”@Liwa没有注意到标记,这是罪过。我编辑了
iteritems()
调用,并将其替换为items()
,这应该可以在Python2和Python3上使用。这将返回“[“Luk:{'4'}”、“Luk:{'2'}”、“Luk:{'0'}”、“Luk:{'1'}”、“Rory_Follin:{'2'}”、“Rory_Follin:{'2'}”、“Rory_Follin:{'10'}”当你跑完我的prgram@Liwa你能发布你的初始namescore
列表吗?看起来您的值和结构可能与您的示例不同。
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']
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']
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']