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