这是我的节目,

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相关问答推荐

根据样本量随机 Select 组内样本

类型注释:pathlib. Path vs importlib. resources. abc. Traversable

使用 Fetch 提交表单到 Django 视图

torch.stack([t1, t1, t1], dim=1)与torch.hstack([t1, t1, t1])之间有什么区别?

使用 GEKKO 使用代码解决最佳时间控制问题时出现 IndexError

如何使用 Selenium by class_name 从大学橄榄球数据中抓取图像 url 列表

`pyspark mllib` 与 `pyspark ml` 包

为什么 List 不能包含多种类型?

获取比较多列的最大值并返回特定值

简单的 get/post 请求在 python 3 中被阻止,但在 python 2 中没有

如何确定一个类的元类?

numpy.ndarray 与 pandas.DataFrame

使用 pytest.fixture 返回模拟对象的正确方法

Pandas 的 EMA 与股票的 EMA 不匹配?

使用打印时,用+连接是否比用,分隔更有效?

如何使用 d.items() 更改 for 循环中的所有字典键?

接收导入错误:没有名为 *** 的模块,但有 __init__.py

如何在 Python 3.2 中退出?

十六进制字符串到 Python 3.2 中的带符号整数?

Pylint 中的模块PyQt5.QtWidgets错误中没有名称QApplication