如果最大的数字在同一个列表中出现多次,我如何将它们全部打印出来?



这是我的程序,

empty_list = []
max_no = 0
for i in range(5):
input_no = int(input("Enter a number: "))
empty_list.append(input_no)
for x in empty_list:
if x > max_no:
max_no = x
high = empty_list.index(max_no)
print ([empty_list[high]])

示例列表:[4, 3, 6, 9, 9]

输出示例:[9]

我怎样才能改变我的程序,打印出在同一个列表中出现的最大数字的所有实例?

期望输出:[9, 9]

为了找到最大的数字,您可以使用Python内置函数max()

max_no = max(empty_list)

为了计算它们,您可以使用count()方法,如下所示:

count_no = empty.count(max_no)

可以存储最大数目和该数目出现的次数。

empty_list = []
max_no = 0
times = 0
for i in range(5):
input_no = int(input("Enter a number: "))
empty_list.append(input_no)
for x in empty_list:
if x > max_no:
max_no = x
times = 1;
elif x == max_no:
times += 1
print([max_no] * times)

你的问题是,给定一个整数列表,你想要一个函数
返回一个最大整数N次的列表,其中N是
在给定列表中出现的次数

def foo(lst):
r = max(lst) # find maximum integer in the list
d = lst.count(r) # find how many times it occurs in the list
return [r for i in range(d)] # create a list with the max int N number of times.

lst = [1,1,1,1,5,5,9]
print(foo(lst)) # prints [9]
lst = [1,1,1,1,5,5]
print(foo(lst)) # prints [5,5]
lst = [4, 3, 6, 9, 9]
print(foo(lst)) # prints [9,9]

最新更新