如何在元素列表中找到最大数量的(可能是唯一的)? [英] How to find the largest number(s) in a list of elements, possibly non-unique?
问题描述
这是我的程序,
item_no = []
max_no = 0
for i in range(5):
input_no = int(input("Enter an item number: "))
item_no.append(input_no)
for no in item_no:
if no > max_no:
max_no = no
high = item_no.index(max_no)
print (item_no[high])
示例输入:[5, 6, 7, 8, 8]
示例输出:8
如何更改程序以在数组中输出相同的最高数字?
预期输出:[8, 8]
只需使用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
初始化.
请注意,第二个代码段的效率比第一个代码段差很多. Python使您比这些显式的,类似于fortran的循环更有效,并且在正确使用它时本身也会更有效. Here is my program, Example input: Example output: How can I change my program to output the same highest numbers in an array? Expected output: Just get the maximum using Note that this will return a list of a single item in case your maximum value appears only once. A solution closer to your current programming style would be the following: with the same results as above of course. Notes
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. 这篇关于如何在元素列表中找到最大数量的(可能是唯一的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!item_no = []
max_no = 0
for i in range(5):
input_no = int(input("Enter an item number: "))
item_no.append(input_no)
for no in item_no:
if no > max_no:
max_no = no
high = item_no.index(max_no)
print (item_no[high])
[5, 6, 7, 8, 8]
8
[8, 8]
max
and then its count
and combine the two in a list-comprehension.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)
-math.inf
should be used instead.