2015-12-23 47 views
3
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] 

我對返回語法感到困惑。return statement confusion ..我不確定語法

  1. 什麼是[keep]?它看起來像一個沒有別的東西的數組支架。

  2. counts[keep]看起來像vector_name[index]。是對的嗎?

最後,爲什麼它會在return語句中乘以兩個值?感謝你的幫助。

+0

可能是這樣'>>>升財產以後= [2] >>> [3] * L [0]''得到[3,3]'。 –

回答

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

在你的情況,keepdices16一個標準的骰子)中最常見的值,counts[keep]是值出現在dices的次數。

如果dices[1, 1, 2, 1, 3, 3],最常見的值是1,它似乎3次,keep = 1counts[keep] = 3,所以你得到[1, 1, 1]

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] 

所以結果是出現在骰子的原始列表中最常見的骰子多次。

+0

它使事情更清楚嗎? –