如何在列表中搜索最高值并输出哪个 str(即 str1、str2 等)在其各自的子列表中具有最高值? 我想要的输出是:最高值是:str5: 5
# list containing string variables in each sublist
list = [["str1"], ["str2"], ["str3"], ["str4"], ["str5"]]
# Go through the list
for i in list:
while True:
try:
val = float(input(f"Enter {i[0]}'s value:"))
except ValueError:
print("Please enter float")
else:
i.append(val)
break
print(list)
output:
Enter str1's value:1
Enter str2's value:2
Enter str3's value:3
Enter str4's value:4
Enter str5's value:5
[['str1', 1.0], ['str2', 2.0], ['str3', 3.0], ['str4', 4.0], ['str5', 5.0]]
答案 0 :(得分:0)
关于这个特定示例,您可以使用以下代码。
max = 0 // zero is always smaller than a max value
maxSublist = [] //define an empty array to store the sublist that is has the max value
for sublist in list: // iterate your list
if float(sublist[1])> max: // if value of list greater than max
max = float(sublist[1]) // makes it the new max so it thresholds later iterations
maxSublist = sublist // store the max sublist so far to the value
print(maxSublist) // when you are done print it
希望对您有所帮助,如有任何问题,请随时提问。