Py学习  »  Python

有没有办法让Python找到用户输入列表中概率最高的下一个数字?

Fraim_rus • 3 年前 • 1585 次点击  

因此,用户在一个字符串中输入n个数字的列表(不超过1000),程序会找到并输出下一个出现概率最高的数字。我是一个初学者,一直在计算可编程性,Python不允许我将列表元素和使用的方法都转换为int:


n = [int(input()), int(input()), int(input()), int(input()), int(input())]
for i in n:
    P = collections.Counter([i]) / len(n)
    print(P)  # The program is supposed to determine the highest possibility and print the respective number afterwards
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129437
文章 [ 1 ]  |  最新文章 3 年前
Samwise
Reply   •   1 楼
Samwise    3 年前

我想你想要的是:

import collections

n = [int(input()) for _ in range(5)]
p = collections.Counter(n)
for i, freq in p.items():
    print(f"{i}: {freq / len(n)}")

参数为 collections.Counter 应该是你的清单;然后你可以迭代 Counter 作为dict,其中键是列表中的项目(用户输入的数字),值是每个项目出现的次数。将计数除以列表的总长度可以告诉您每个项目出现的时间百分比。

1
2
3
2
2
1: 0.2
2: 0.6
3: 0.2

如果你只想得到一个出现频率最高的数字,可以选择 max 这样地:

print(f"Most frequent: {max(p, key=p.get)}")