这是我的节目,

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初始化.

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.

Python-3.x相关问答推荐

如何创建一个polars gramme,给出列表中的列名,

使用Pandas 阅读Excel定义的名称和单元格值(&Q;)

如何计算累积几何平均数?

我正在try 从 10*3 矩阵中删除随机值并将其变为 10*2 矩阵

PyQt5 中耦合滑块和拨号小部件.解决结果不一致的问题

我想使用命令提示符安装 cv2

通过匹配第一列的行值,逐个单元格地添加两个Pandas 数据框中的浮点数

在 pytest 中,如何测试 sys.exit('some error message')?

将两列合并为一列,将它们制成字典 - pandas - groupby

为什么 return node.next 会返回整个链表?

对齐文本文件中的列

python中两个连续的yield语句如何工作?

python tkInter 浏览文件夹按钮

如何用pymongo连接远程mongodb

如果一个失败,如何取消收集中的所有剩余任务?

TypeError:列表索引必须是整数或切片,而不是列表

在 Python 3 中获取所有超类

如何使用 Python 订阅 Websocket API 通道?

命名参数可以与 Python 枚举一起使用吗?

python中的绝对导入是什么?