只需使用max
获得最大值,然后使用count
,并将两者结合在一个列表中.
item_no = [5, 6, 7, 8, 8]
max_no = max(item_no)
highest = [max_no for _ in range(item_no.count(max_no))]
print(highest) # -> [8, 8]
请注意,如果最大值只出现一次,这将返回单个项目的列表.
更接近您当前编程风格的解决方案如下:
item_no = [5, 6, 7, 8, 8]
max_no = 0 # Note 1
for i in item_no:
if i > max_no:
max_no = i
high = [i]
elif i == max_no:
high.append(i)
当然,结果与上述相同.
笔记
- 我假设你只处理N*(1, 2, ...)个数字.如果不是这样,则应使用
-math.inf
初始化.
Note that the second code snippet is less efficient than the first by quite a margin. Python allows you to be more efficient than these explicit, fortran-like loops and it is more efficient itself when you use it properly.