python - 返回语句困惑..我不确定语法

标签 python probability

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]

我对返回的语法感到困惑。

  1. 什么是[keep]?它看起来像一个没有其他任何东西的数组括号。

  2. 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/

相关文章:

python - 类型为 'f' 的对象的未知格式代码 'unicode'

python - 如何将包添加到系统路径进行测试

Python:索引 float ?

Python 新手 : manipulating arrays

language-agnostic - 选择最不可能出现在真实数据中的魔术字节

python - 如何在 matplotlib 饼图中设置楔形边框?

python - 在 Python 中识别视觉上相似的字符串

r - 概率计算

评估用户 react 的算法