def most_common(dices):
"""
Returns the dices that are most common
In case of a draw, returns the lowest number
"""
counts = Counter(dices)
keep = max(counts.iteritems(), key=operator.itemgetter(1))[0]
return [keep] * counts[keep]
我对返回的语法感到困惑。
什么是[keep]
?它看起来像一个没有别的数组括号。
counts[keep]
看起来像vector_name[index]
。是吗?
最后,为什么它会在返回声明中将两者相乘?谢谢你的帮助。
答案 0 :(得分:3)
让我们一步一步走。
首先我们导入:
>>> from collections import Counter
>>> import operator
这些是我们的示例骰子:
>>> dices = [3, 5, 6, 2, 3, 4, 3, 3]
Counter
计算每个人中有多少人:
>>> counts = Counter(dices)
>>> counts
Counter({3: 4, 2: 1, 4: 1, 5: 1, 6: 1})
这会得到最大数量的骰子:
>>> keep = max(counts.iteritems(), key=operator.itemgetter(1))[0]
>>> keep
3
顺便说一下,你得到的号码与:相同
>>> keep = counts.most_common()[0][0]
将keep
放入列表中:
>>> [keep]
[3]
此词典查找返回3
出现的次数:
>>> counts[keep]
4
您可以将列表与整数相乘:
>>> [3] * 4
[3, 3, 3, 3]
或:
>>> [keep] * counts[keep]
[3, 3, 3, 3]
所以结果是最常见的骰子,就像它在原始骰子列表中出现的次数一样多。
答案 1 :(得分:0)
[keep]
是一个包含单个元素(keep
)的列表,例如如果keep = 4
,则[keep]
为[4]
。
在python中,您可以将list
乘以数字:
>>> l = [1]
>>> l * 3
[1, 1, 1]
所以[keep] * counts[keep]
基本上是:
[keep, keep, ..., keep]
您有counts[keep]
次keep
。
在您的情况下,keep
是dices
中最常见的值(标准骰子为1
至6
),counts[keep]
为数字该值出现在dices
中的次数。
如果dices
为[1, 1, 2, 1, 3, 3]
,则最常见的值为1
,并显示3
次keep = 1
和counts[keep] = 3
,因此您得到[1, 1, 1]
。