此代码采用一个有序(从最高分到最低分)的元组列表,并收集最高,第二高和第三最高得分者的姓名和得分。如果他们的关系相同,则两个名称都将附加到同一列表中。
myresults=[('Raven', '18'), ('Cobra', '8'), ('Lion', '6'), ('Otter', '2')]
FirstScore=myresults[0][1]
SecondHighestScore=0
ThirdHighestScore=0
for i in myresults:
if i[1]==FirstScore:
FirstPlacePatrols.append(i[0])
for i in myresults:
print(i[1])
print(repr(i[1]))
if int(i[1])<int(FirstScore):
if int(i[1])>=SecondHighestScore:
print(i[1])
i[1]=SecondHighestScore
SecondPlacePatrols.append(i[0])
for i in myresults:
if int(i[1])<SecondHighestScore:
if int(i[1])>=ThirdHighestScore:
i[0]=ThirdHighestScore
ThirdPlacePatrols.append(i[0])
print(FirstPlacePatrols)
print(FirstScore)
print(SecondPlacePatrols)
print(SecondHighestScore)
print(ThirdPlacePatrols)
print(ThirdHighestScore)
但是,
i[1]=SecondHighestScore
产量
TypeError: 'tuple' object does not support item assignment
尽管
print(repr(i[1]))
屈服,
'18'
显然不是元组。
答案 0 :(得分:1)
您无法更改tuple()s-它们是不可变的。您可以创建一个新的。或者,您可以使用itertools.groupby
将元组组合在一起并进行一些选择性输出:
myresults=[('Raven', '18'), ('Cobra', '8'), ('Lion', '6'), ('Swine', '6'), ('Otter', '2')]
from itertools import groupby
grped = groupby(myresults, lambda x: int(x[1]))
# create a dict for all results
result_dict = {}
for key in grped :
result_dict[key[0]] = [value for value,_ in key[1]]
# print top 3 results:
for k in sorted(result_dict,reverse=True):
print(k)
print(result_dict[k])
# whole dict
print(result_dict)
输出:
18
['Raven']
8
['Cobra']
6
['Lion', 'Swine']
# whole dict
{18: ['Raven'], 8: ['Cobra'], 6: ['Lion', 'Swine'], 2: ['Otter']}
使用collections.defaultdict
解决此问题的第二种方法:
myresults=[('Raven', '18'), ('Cobra', '8'), ('Lion', '6'), ('Swine', '6'), ('Otter', '2')]
from collections import defaultdict
result_dict = defaultdict(list)
for value,key in myresults:
result_dict[int(key)].append(value)
for k in sorted(result_dict,reverse=True):
print(k)
print(result_dict[k])
print(result_dict)
18
['Raven']
8
['Cobra']
6
['Lion', 'Swine']
2
['Otter']
# whole dict
defaultdict(<class 'list'>, {18: ['Raven'], 8: ['Cobra'],
6: ['Lion', 'Swine'], 2: ['Otter']})
Doku:
答案 1 :(得分:0)
这是我的解决方法:
from collections import defaultdict
given_list = [('Raven', '18'), ('Cobra', '8'), ('Lion', '6'), ('Python', '6'),('Otter', '2')]
reversed_dict = defaultdict(list)
for key,value in given_list:
reversed_dict[int(value)].append(key)
for k in reversed(sorted(reversed_dict)[-3:]):
print(k,reversed_dict[k])
输出:
18 ['Raven']
8 ['Cobra']
6 ['Lion', 'Python']