有两个相应的一对一关系列表。
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]
答案 0 :(得分:6)
这应该可以解决问题:
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)
答案 1 :(得分:2)
您可以在一行中执行此操作,但如果您分阶段执行此操作则更容易阅读。首先选择分数大于阈值的项目,然后对它们进行排序。
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)))
答案 2 :(得分:1)
如果您想要排序的输出,也可以使用OrderedDict
表单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)