【问题标题】:If the largest number occurs more than once in the same list, how do I print them all out?如果最大的数字在同一个列表中多次出现,我如何将它们全部打印出来?
【发布时间】:2021-02-23 15:26:06
【问题描述】:

这是我的程序,

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]

【问题讨论】:

  • print out all the largest numbers that occur more than once 是什么意思如果给你[1,1,1,1,5] 呢?
  • 您想要答案 (2, 9) 还是 [9, 9]? (2, 9) 表示 9 出现 2 次​​span>
  • @taesu 我想打印出[5]
  • @PascalFares [9, 9]。基本上是数组中最大数的所有实例。

标签: python arrays python-3.x


【解决方案1】:

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

max_no = max(empty_list)

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

count_no = empty.count(max_no)

【讨论】:

    【解决方案2】:

    您可以存储最大数量和该数字出现的次数。

    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)
    

    Demo

    【讨论】:

      【解决方案3】:

      你在问,给定一个包含整数的列表,你想要一个函数
      返回具有最大整数 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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 1970-01-01
        相关资源
        最近更新 更多