如何比较元组元素中的一个组件?函数输入一个元组(str,int)I以仅访问int



就像我提到的,我只想比较int,我尝试过的代码导致

类型错误:'>'在"int"one_answers"tuple"的实例之间不支持

输入:[('Mikayla',20(,('Kevin',25(,('Tristan',10(,(Moe',30(]

输出:[('Moe',30(,('Kevin',25(,('Mikayla',20(]

winners = []
max = 0 
int_val = 0
for i in range (0,2):            # find 3 values
for j in range(len(scores)):  # look thru all of the tuples
if scores[j][1] > max:     #compare int val from tup to max
max = scores[j]         # assign a full tup (str,in) to  max 
winners.append(max)      #append max to new array
scores.remove(max)      #remove from old array
return winners             #return list of winner tuples (str,int)

由于max是一个元组,您需要对其进行索引以获得要与之比较的分数:

if scores[j][1] > max[1]:

另外,不要将max用作变量名。它是一个内置函数的名称。

相关内容

最新更新