有两个一一对应的列表。
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]
请您参考如下方法:
这应该可以解决问题:
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)
