按字母顺序对列表排序,同时保留以前的索引

2024-04-20 14:21:49 发布

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

我有一个个人项目,其中我有一个名单的名字和3个分数对应的某个名字。然而,我想'排序'这个名单按字母顺序,同时保持以前的索引,以便我可以链接的分数。 我想实现的是能够将这个列表按字母顺序排序,并打印出与姓名相对应的分数,我不知道如何才能使这个列表更加简洁和信息丰富。在

以下是我的一些代码:

Names = ['Fred', 'John', 'Sally']
Scores = [1,5,9,2,4,6,3,6,5]
for i in range(0, len(Names)):
    print("The score(s) for", Names[i], "is:", Scores[i], Scores[i+3], Scores[i+6])`

因此,例如,当排序时,我对该程序的首选结果是:

The score(s) for John is: 5, 4, 6 etc...


Tags: the项目列表fornames排序顺序is
3条回答

一堆任意的list在这里使用是错误的数据结构。创建一个字典,其中包含用户名的键和他们的分数列表的值。如果必须从给定的NamesScores开始,可以这样做:

>>> Names=['Fred', 'John', 'Sally']
>>> Scores=[1,5,9,2,4,6,3,6,5]
>>> Scores = [Scores[i:i+3] for i in range(0, len(Scores), 3)]
>>> all_scores = {k:v for k,v in zip(Names, Scores)}
>>> all_scores
{'Sally': [3, 6, 5], 'John': [2, 4, 6], 'Fred': [1, 5, 9]}

现在你可以sort和{}任意你喜欢的字典。

如果你假设每一个名字都是唯一的,那么这个过程可能会很快。您只需要使用未排序列表中的索引。

names = ['Fred', 'John', 'Sally', 'Alex']
scores = [1,5,9,7, 2,4,6,8, 3,6,5,9]

l = len(names)
for e in sorted(names):
    i = names.index(e) # index in unsorted list
    print "The score for", e, "is:", scores[i], scores[i+l], scores[i+2*l]

首先重新排列数据模型,如下所示:

Names = ['Fred', 'John', 'Sally']
Scores = [1,5,9,2,4,6,3,6,5]

data = {}
for index, name in enumerate(Names):
    data[name] = [Scores[(index * 3)], Scores[(index * 3) + 1], Scores[(index * 3) + 2]]

现在data包含:

^{pr2}$

现在你可以随心所欲了。要以排序方式打印姓名和分数,您可以:

for name in sorted(data.keys()):
    print name, date[name]

相关问题 更多 >