def print_most_numbers_occurrences(numbers_str):
number_list = numbers_str.split()
for i in number_list:
i=max(number_list,key=number_list.count)
print(i)
def test_print_most_numbers_occurrences():
print_most_numbers_occurrences('2 3 40 1 5 4 3 3 9 9')
print_most_numbers_occurrences('9 30 3 9 3 1 4')
print_most_numbers_occurrences('19 30 13 4 9 3 1 4')
def main():
test_print_most_numbers_occurrences()
main()
输出:
3
9
4
我希望'9 30 3 9 3 1 4'
得到所有最重复的数字:9和3出现两次,因此不仅要报告两次出现9
输出如下:
3
9
3
4
答案 0 :(得分:4)
首先:当您使用for
时,您不需要max
- 循环。它已经为你做到了。
第二:如果你想拥有多个值,那么max
并不是一个好的选择。对于这类计数操作,您应该使用collections.Counter
(它还可以避免多次计算出现次数)。
from collections import Counter
def print_most_numbers_occurrences(numbers_str):
number_list = numbers_str.split()
# count the occurrences
cnts = Counter(number_list)
# Get the maximum count
maximum_cnt = max(cnts.values())
# print all values that have the "maximum" count
print(*[val for val, cnt in cnts.items() if cnt == maximum_cnt])
输入的测试打印出来:
3
9 3
4
如果您更喜欢简单的循环而不是理解(或者您使用不带print
函数的python-2.x),您也可以使用:
def print_most_numbers_occurrences(numbers_str):
number_list = numbers_str.split()
cnts = Counter(number_list)
maximum_cnt = max(cnts.values())
for value, cnt in cnts.items():
if cnt == maximum_cnt:
print(value)
给出:
3
9
3
4
答案 1 :(得分:0)
from collections import Counter
a = ('2 3 40 1 5 4 3 3 9 9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4')
for x in a:
x = x.split()
b = Counter(x)
z = max(b.values())
for k in b.keys():
if b[k] == z:
print(k)
输出:
3
9
3
4
如果您想要其他输出
from collections import Counter
a = ('2 3 40 1 5 4 3 3 9 9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4')
k = []
for x in a:
x = x.split()
b = Counter(x)
z = max(b.values())
k.append([f for f in b.keys() if b[f] == z])
print(k)
输出
[['3'], ['9', '3'], ['4']]
使用功能
from collections import Counter
def maxmy(sequences):
k = []
for x in sequences:
x = x.split()
b = Counter(x)
z = max(b.values())
k.append([f for f in b.keys() if b[f] == z])
return k
maxmy(('2 3 40 1 5 4 3 3 9 9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4'))
输出
[['3'], ['9', '3'], ['4']]