我有一个分数列表,我希望找到列表中的最高值(在下面的示例中,它是值80)。
scores = [60,29,60,43,10,9,80,45,23,80,56,4]
highest_score = 0
for i in scores:
if i >= highest_score:
highest_score = i
print (highest_score, scores.index(highest_score) )对于highest_scores,它返回[60,60,80,80],而我只想获得最高值的80。对于scores.index(highest_score),它为我提供了索引[0,0,6,6],而我希望获得最高值的索引-它应该是[6,6]。
我如何改进我的代码以获得期望的结果?
发布于 2021-05-03 01:19:50
如果您正在寻找[60,29,60,43,10,9,80,45,23,80,56,4]中最高值的索引,我想您的意思是您想要:[6, 9]。
假设您想要算法的“本机”实现,而不必求助于max()函数,并且您想要索引,我建议您使用enumerate(scores)
scores = [60,29,60,43,10,9,80,45,23,80,56,4]
highest_score = scores[0]
indexes = []
for i, s in enumerate(scores):
if s > highest_score:
indexes = []
if s >= highest_score:
indexes.append(i)
highest_score = s
print(highest_score, indexes)结果:
80 [6, 9]发布于 2021-05-03 01:06:50
您可以通过以下方式找到最大值:
max(scores)返回80。
发布于 2021-05-03 01:09:44
您正在进行的错误是在用于打印语句的缩进中。它应该在循环之外。尝试以下代码:
scores = [60, 29, 60, 43, 10, 9, 80, 45, 23, 80, 56, 4]
highest_score = 0
for i in scores:
if i >= highest_score:
highest_score = I
# find all indices of the highest_score
indices = [i for i, x in enumerate(scores) if x == highest_score]
print(highest_score, indices)我还编写了一个列表理解,用于查找列表中得分最高的所有索引,因为您的代码将只返回第一次出现的索引。
输出:
80 [6, 9]https://stackoverflow.com/questions/67359024
复制相似问题