Mar*_*k K 1 python dictionary list
有两个相应的1对1关系列表.
names = ["David", "Peter", "Kate", "Lucy", "Kit", "Jason", "Judy"]
scores = [1,1,0.8,0.2,0.4,0.1,0.6]
Run Code Online (Sandbox Code Playgroud)
我想展示得分超过0.5并且显示在1行中的人:
Peter (1 point), David (1 point), Kate (0.8 point), Judy (0.6 point)
Run Code Online (Sandbox Code Playgroud)
我尝试的是:
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
Run Code Online (Sandbox Code Playgroud)
它给:
[('Peter', 1), ('David', 1), ('Kate', 0.8), ('Judy', 0.6), ('Kit', 0.4), ('Lucy', 0.2), ('Jason', 0.1)]
Run Code Online (Sandbox Code Playgroud)
怎么能进一步得到想要的结果呢?注意:需要从大到小的排序结果.
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]
Run Code Online (Sandbox Code Playgroud)
这应该做的伎俩:
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))
Run Code Online (Sandbox Code Playgroud)
输出:
Irene (1.2 points), David (1 points), Peter (1 points), Kate (0.8 points), Mark (0.7 points), Judy (0.6 points)
Run Code Online (Sandbox Code Playgroud)