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]
。是吗?
最后,为什么要在 return 语句中将两者相乘?感谢您的帮助。
最佳答案
让我们一步一步来。
首先我们导入:
>>> 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]
因此结果是最常见的骰子,与它在原始骰子列表中出现的次数一样多。
关于python - 返回语句困惑..我不确定语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34432454/