简体   繁体   中英

How to find the largest number(s) in a list of elements, possibly non-unique?

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.

You can do it even shorter:

item_no = [5, 6, 7, 8, 8]
#compute once - use many times
max_item = max(item_no)
print(item_no.count(max_item) * [max_item])

Output:

[8, 8]

You could use list comprehension for that task following way:

numbers = [5, 6, 7, 8, 8]
maxnumbers = [i for i in numbers if i==max(numbers)]
print(*maxnumbers,sep=',')

output:

8,8

* operator in print is used to unpack values, sep is used to inform print what seperator to use: , in this case.

EDIT: If you want to get indices of biggest value and call max only once then do:

numbers = [5, 6, 7, 8, 8]
biggest = max(numbers)
positions = [inx for inx,i in enumerate(numbers) if i==biggest]
print(*positions,sep=',')

Output:

3,4

As you might check numbers[3] is equal to biggest and numbers[4] is equal to biggest .

  1. Count the occurrence of max number

  2. iterate over the list to print the max number for the range of the count (1)

Hence :

item_no = [5, 6, 7, 8, 8]
counter = item_no.count(max(item_no))      # 2
print([max(item_no) for x in range(counter)])   

OUTPUT :

[8, 8]

通过查找等于最大值的项目,可以在一行中解决此问题:To提高性能 store max in var Mvalue=max(item_no) [i for i in item_no if i==Mvalue]

I think it would be better if we evaluate the max in the array and its count in one iteration

def maxs(iterable):
    max = None
    count = 0
    for index, value in enumerate(iterable):
        if index == 0 or value >= max:
            if value != max:
                count = 0
            max = value
            count += 1
    return count * [max]


print (maxs([5, 6, 7, 8, 8]))   # [8, 8]
print (maxs([3, 2, 4, 5, 1, 2, 4, 5, 2, 5, 0])) # [5, 5, 5]
print (maxs([])) # []

Give it a Try!!

I think there is no possible way to find all max numbers with just a single line BUT it will kinda work with this first of all we will sort the list in ascending then do this

yourList = [7,7,76,4,54,4,5,234,5,56,7,234,34,234,234]

yourList.sort()
ind = yourList.index(max(yourList))
for i in range(ind,ind+(len(yourList)-ind)):
    print(yourList[i])


in this basically we will get the index of the first max number then we will subtract it by the lenght of the list and we will get how many indexes to plus to get all the max digits

OR

there is one another way to do it in this way

lis = [1,2,3,12,12,1,12,3,4,5,6,12, 12]
count = lis.count(max(lis))
loop = [print(max(lis), end=" ") for i in range(count)]

in this way we will get how many times the max number has occurred in the list and print it that many time

If you want to do without using inbuilt function and stick to your way then below is useful

item_no = [0,5,6,2,6,5,6,7,8,1,2,8]
max_no = 0
list = []
for no in item_no:
    if no==max_no:
         list.append(no)  #append the list with the new number
    elif no > max_no:
       max_no = no
       list=[no]         # reset the list with new highest number
print(list)--->output[8,8]

One can use nested list comprehensions. Check this out.

numbers = [5,6,7,8,8]
maxlist = [num for num in numbers if True not in [True for i in numbers if i > num]]

Output : maxlist = [8,8]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM