Python按值对两个对应列表进行排序(一个列表的值)

2024-05-18 19:55:03 发布

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

有两个对应的1对1关系列表。你知道吗

names = ["David", "Peter", "Kate", "Lucy", "Kit", "Jason", "Judy"]
scores = [1,1,0.8,0.2,0.4,0.1,0.6]

我想显示得分超过0.5的人,并在1行中显示:

Peter (1 point), David (1 point), Kate (0.8 point), Judy (0.6 point)

我尝试的是:

import operator

names = ["David", "Peter", "Kate", "Lucy", "Kit", "Jason", "Judy"]
scores = [1,1,0.8,0.2,0.4,0.1,0.6]

dictionary = dict(zip(names, scores))

dict_sorted = sorted(dictionary.items(), key=operator.itemgetter(1), reverse=True)

print dict_sorted

它给出:

[('Peter', 1), ('David', 1), ('Kate', 0.8), ('Judy', 0.6), ('Kit', 0.4), ('Lucy', 0.2), ('Jason', 0.1)]

如何进一步取得所需的结果?注意:需要从大到小排序结果。你知道吗

2个较长的测试列表:

names = ["Olivia","Charlotte","Khaleesi","Cora","Isla","Isabella","Aurora","Amelia","Amara","Penelope","Audrey","Rose","Imogen","Alice","Evelyn","Ava","Irma","Ophelia","Violet"]
scores = [1.0, 1.0, 0.8, 0.2, 0.2, 0.4, 0.2, 0.0, 1.0, 0.2, 0.4, 0.2, 1.0, 0.0, 0.8, 0.0, 1.0, 0.0, 0.6]

Tags: 列表dictionarynamesoperatordictkitpeterpoint
3条回答

你可以在一行中完成,但如果你分阶段完成,阅读起来就容易多了。首先选择得分大于阈值的项目,然后对其排序。你知道吗

import operator

names = ["Olivia","Charlotte","Khaleesi","Cora","Isla","Isabella","Aurora","Amelia","Amara","Penelope","Audrey","Rose","Imogen","Alice","Evelyn","Ava","Irma","Ophelia","Violet"]
scores = [1.0, 1.0, 0.8, 0.2, 0.2, 0.4, 0.2, 0.0, 1.0, 0.2, 0.4, 0.2, 1.0, 0.0, 0.8, 0.0, 1.0, 0.0, 0.6]

threshold = 0.5
lst = [(name, score) for name, score in zip(names, scores) if score > threshold]
lst.sort(reverse=True, key=operator.itemgetter(1))
print(lst)

输出

[('Olivia', 1.0), ('Charlotte', 1.0), ('Amara', 1.0), ('Imogen', 1.0), ('Irma', 1.0), ('Khaleesi', 0.8), ('Evelyn', 0.8), ('Violet', 0.6)]

以下是单行版本:

print(sorted(((name, score) for name, score in zip(names, scores) if score > 0.5), reverse=True, key=operator.itemgetter(1)))

这应该可以做到:

names = ["David", "Peter", "Kate", "Lucy", "Kit", "Jason", "Judy", "Mark", "John", "Irene"]
scores = [1,1,0.8,0.2,0.4,0.1,0.6,0.7,0.3,1.2]

print(', '.join('{} ({} points)'.format(name, points) for name, points in sorted(zip(names, scores), key=__import__('operator').itemgetter(1), reverse=True) if points > 0.5))  

输出:

Irene (1.2 points), David (1 points), Peter (1 points), Kate (0.8 points), Mark (0.7 points), Judy (0.6 points)

如果需要排序的输出,还可以使用OrderedDictform collections模块。你知道吗

from collections import OrderedDict

names = ["David", "Peter", "Kate", "Lucy", "Kit", "Jason", "Judy"]
scores = [1,1,0.8,0.2,0.4,0.1,0.6]

dict_sorted = OrderedDict((k, v) for k, v in zip(names, scores) if v > 0.5)
print(', '.join('{} ({} points)'.format(k, v) for k, v in dict_sorted.items()))

印刷品: David (1 points), Peter (1 points), Kate (0.8 points), Judy (0.6 points)

相关问题 更多 >

    热门问题