如何在元素列表中找到最大数量的(可能是唯一的)? [英] How to find the largest number(s) in a list of elements, possibly non-unique?

查看:105
本文介绍了如何在元素列表中找到最大数量的(可能是唯一的)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的程序,

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)

具有与上述相同的结果.

注释

  1. 我假设您只处理N *( 1、2,... )个数字.如果不是这种情况,应改用-math.inf初始化.


请注意,第二个代码段的效率比第一个代码段差很多. Python使您比这些显式的,类似于fortran的循环更有效,并且在正确使用它时本身也会更有效.

Here is my program,

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])

Example input: [5, 6, 7, 8, 8]

Example output: 8

How can I change my program to output the same highest numbers in an array?

Expected output: [8, 8]

解决方案

Just get the maximum using 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]

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:

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)

with the same results as above of course.

Notes

  1. I am assuming that you are dealing with N* (1, 2, ...) numbers only. If that is not the case, initializing with -math.inf should be used instead.


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆