'<' 在 str 和 int 的实例之间不受支持
'<' not supported between instances of str and int
我想找出一组人中的最低分。
我的代码:
list = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
min_score = list[0][1]
for x in list:
for y in x:
if (y < min_score):
min_score=y
print(min_score)
我应该怎么做?
您正在遍历 x
的 每个 元素,而您实际上只关心 x[1]
:
for x in list:
if x[1] < min_score:
min_score = x[1]
您还可以解压缩每个子列表,以便为值提供更易于使用的名称:
for name, score in list:
if score < min_score:
min_score = score
list
是 python 中的内置数据类型,因此您应该将变量重命名为其他名称,例如 l
在您的第一个 for 循环中,您正在执行 for x in list
,因此您将 x 分配给列表的第一个元素,即 ['Radhe', 99]
。在您的第二个 for 循环中,您将遍历 x 中的每个项目,其中第一个是 'Radhe'
,因此您正在将一个 int 与一个字符串进行比较。
考虑到这一点,您可以将代码重写为:
l = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
min_score = l[0][1]
for x in l:
if (x[1] < min_score):
min_score=x[1]
print(min_score)
输出:
89
或者,您可以使用列表理解在一行中完成所有操作:
min_score = min([x[1] for x in l])
试试这个
given_list = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
print(min(given_list, key=lambda x: x[1])[1])
我想找出一组人中的最低分。
我的代码:
list = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
min_score = list[0][1]
for x in list:
for y in x:
if (y < min_score):
min_score=y
print(min_score)
我应该怎么做?
您正在遍历 x
的 每个 元素,而您实际上只关心 x[1]
:
for x in list:
if x[1] < min_score:
min_score = x[1]
您还可以解压缩每个子列表,以便为值提供更易于使用的名称:
for name, score in list:
if score < min_score:
min_score = score
list
是 python 中的内置数据类型,因此您应该将变量重命名为其他名称,例如l
在您的第一个 for 循环中,您正在执行
for x in list
,因此您将 x 分配给列表的第一个元素,即['Radhe', 99]
。在您的第二个 for 循环中,您将遍历 x 中的每个项目,其中第一个是'Radhe'
,因此您正在将一个 int 与一个字符串进行比较。
考虑到这一点,您可以将代码重写为:
l = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
min_score = l[0][1]
for x in l:
if (x[1] < min_score):
min_score=x[1]
print(min_score)
输出:
89
或者,您可以使用列表理解在一行中完成所有操作:
min_score = min([x[1] for x in l])
试试这个
given_list = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
print(min(given_list, key=lambda x: x[1])[1])