Python 对列表中的某些项进行计数,然后在if语句中使用该输出

Python 对列表中的某些项进行计数,然后在if语句中使用该输出,python,arrays,python-2.7,list,if-statement,Python,Arrays,Python 2.7,List,If Statement,我试图开发一个程序,从用户那里获取大量输入,然后计算用户输入该数字的特定次数,然后使用该信息确定最常见的是什么 from collections import Counter results = [] while len(results)<7: entered=int(raw_input('enter results:')) results.append(entered) print results distribution = Counter(results) pr

我试图开发一个程序,从用户那里获取大量输入,然后计算用户输入该数字的特定次数,然后使用该信息确定最常见的是什么

from collections import Counter
results = []
while len(results)<7:
    entered=int(raw_input('enter results:'))
    results.append(entered)

print results

distribution = Counter(results)

print distribution
从这里,我希望能够获取最后给出的信息,并告诉用户我最常用的是哪一种,我知道用户可以从计数器输出中看到它,但这是我被赋予的任务的一部分。我在考虑使用一些类似于

if 2 >= 4:
     print 'most common.'

我不完全确定distribution的输出。这是最常见的,但如果这不起作用,这里有一个相当简单的循环来完成这项工作

most_common = 0
for i in distribution:
    if distribution[i] > distribution[most_common]:
        most_common = i

print most_common
此外,如果您需要知道该数字的频率是否超过输入的一半,您可以

if distribution[most_common] > 7./2:
    more_than_half = True
else:
    more_than_half = False

根据我的理解,你想要的是:

from collections import Counter

distribution = Counter({2: 2, 1: 1, 3: 1, 4: 1, 5: 1, 6: 1})

most_common_item = distribution.most_common(1)
print('most common is: {}'.format(most_common_item[0][0]))  # Output: most common is: 2

你看过
发行版的输出了吗?比如说最普通的(1)
?通过
2>=4
你的意思是一个项目只有出现至少4次才是“最普通的”吗?@ettanany是的,我只是把它作为一个例子,因为我只有6个输入可以改变。Jon,我刚刚尝试了“发行版。最普通的(1)”它工作,但不是我想要的,那只是显示了最常见的是什么,我想根据最常见的是什么给用户反馈。
most_common=distribution.most_common(1)
会给你
[(2,2)]
,你可以做
打印('most common is{}'。格式(most_common[0][0])
!不是你想要的吗?另外,因为它不太清楚(至少对我来说),我要指出,在循环中,
I
是你输入的不同数字的列表,
distribution[I]
I
发生的频率。我基本上知道你用一个额外的步骤做了什么,因此,一旦我们找到了最常见的,然后将其放入if语句中,看看它是否在一定时间内出现,在本例中是4,例如“if most_common>4:print this is biased”,正如我在第二个代码块中所说的那样,您希望使用
if distribution[most_common]
而不是
most_common
。很高兴我能帮上忙:)我刚刚在中添加了一个错误“Traceback(最近一次调用):文件“task 2.py”,第21行,在if发行版(最常见)>4:TypeError:“Counter”对象不可调用“它应该有方括号”。其
分布[最常见]
from collections import Counter

distribution = Counter({2: 2, 1: 1, 3: 1, 4: 1, 5: 1, 6: 1})

most_common_item = distribution.most_common(1)
print('most common is: {}'.format(most_common_item[0][0]))  # Output: most common is: 2