列表中最大数字的出现

时间:2019-10-29 10:18:05

标签: python python-3.x find-occurrences

因此,在互联网上搜索了几个小时后,尽管我发现了一些相关的信息,但仍然找不到我想要的东西。在我的代码中,我提供了6个输入。输入之后,我设法将它们插入到list()中,并使用max()找到最大的数字。我需要找到频率(该数字被重复多少次,而不是该数字是多少)。在谷歌,我发现喜欢什么是最重复的数字,但没有多少次重复。例如,如果用户输入1,1,2,2,2,3,则max()的第一个输出已经为3。如何获得最大数3的频率,该频率仅重复一次。所以我正在寻找的输出是1。它将看起来像这样:     最大数量是:3     出现次数最多的是:1

I have already managed to get biggest number output as I mentioned, but not the occurrence. Waiting for your response:    
Number_1 = int(input("Please type your 1st number: "))
Number_2 = int(input("Please type your 2nd number: "))
Number_3 = int(input("Please type your 3rd number: "))
Number_4 = int(input("Please type your 4th number: "))
Number_5 = int(input("Please type your 5th number: "))
Number_6 = int(input("Please type your 6th number: "))

listNumbers = [Number_1, Number_2, Number_3, Number_4, Number_5, Number_6]


maxNumber = max(listNumbers)
print("The largest number is ", maxNumber)

#Most occurrent
def most_frequent(List):
    return max(set(List), key = List.count)

*THE OCCURRENCE NUMBER CODE GOES HERE*

3 个答案:

答案 0 :(得分:1)

print(listNumbers.count(max(listNumbers)))

就这么简单。 ?

答案 1 :(得分:1)

仅获取已找到的最大数量的计数:

maxNumberCount = listNumbers.count(maxNumber)
print(maxNumberCount)

答案 2 :(得分:0)

您可以使用如下计数器:

maxNumber = max(listNumbers)
print("The largest number is", maxNumber)

counter = 0
for i in listNumbers:
    if i == maxNumber:
        counter += 1

print("The largest number occurs", counter, "times")

一个更好的解决方案涉及列表理解:

counter = sum([1 if i == maxNumber else 0 for i in listNumbers])