天天看點

for result in zip(*results): ensemble_tag = Counter(result).most_common(1)[0][0]

1.先來說說counter()函數

2.再來說說整句話是什麼意思。

一、Counter函數,顧名思義就是計算函數,參數可以是list,也可以是dict比較靈活

*計算字元串中字母個數
>>> c = Counter('abcdeabcdabcaba')  # count elements from a string
>>> c.most_common(3)                # 輸出數量最多的前三個
[('a', 5), ('b', 4), ('c', 3)]

*對Counter對象c進行元素篩選
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']

*
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'

*求Counter對象的總長度
>>> sum(c.values())                 # total of all counts
15

*求Counter對象中某個元素的數量
>>> c['a']                          # count of letter 'a'
5

*将新的字元串融入Counter對象
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7

*移除元素
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0

*兩個Counter對象合并  用update()函數
>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9

*清除
>>> c.clear()                       # empty the counter
>>> c
Counter()

*元素扣除
>>> c['b'] -= 2                     # reduce the count of 'b' by two
将Counter對象中國元素“b”的個數減少兩個

      

二、再來說說整句話是什麼意思。

這裡results是一個lists,含有四個list,四個list長度一緻

for result in zip(*results):   就是對results進行周遊,每次四個list同時取出一個元素,得到一個tuple

ensemble_tag = Counter(result).most_common(1)[0][0]     

中Counter(result) 就是對着四個元素組成的tuple進行計算,傳回一個Counter對象,近似一個dict

most_common(1) 就是去計算結果中數量最多的一個元素及其對應數量,傳回結果是個list

Counter(result).most_common(1)[0][0]     中第一個[0]是取list中第一個元素,因為這裡隻取了結果中最多的一個元素(.most_common(1))是以隻有這一個。第二個[0]是q:取出的結果實際上包含元素和對應的數量,我們隻需要這個元素是什麼。

eg:隻給出第一個循環的結果。

from collections import Counter
a = [[1,2,3,4,5,6],[2,3,4,5,6,7],[2,4,5,7,8,9],[4,5,6,10,11,12]]
for r in zip(*a):
    en = Counter(r)
    en1 = Counter(r).most_common(1)
    en2 = Counter(r).most_common(1)[0]
    en3 = Counter(r).most_common(1)[0][0]
    print(r)
    print(en)
    print(en1)
    print(en2)
    print(en3)

》》(1, 2, 2, 4)
》》Counter({2: 2, 1: 1, 4: 1})
》》[(2, 2)]
》》(2, 2)
》》2
           

繼續閱讀