data = Counter(list_name)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
有人可以逐步解释第三行吗?
谢谢。
答案 0 :(得分:0)
如果v
等于data
字典值中的最大值,则返回get_mode
中所有键的列表,其中v
是该键的值输入字典
注意:data
和get_mode
都是字典,因此第二行似乎不必要
答案 1 :(得分:0)
from collections import Counter
# Example
# consider a list containing elements as below
list_name = ['orange', 'apple', 'apple', 'orange', 'apple']
data = Counter(z) # Once initialized, counters are accessed just like dictionaries
print(data) # Counter({'apple': 3, 'orange': 2})
get_mode = dict(data) # converting to the dictionary
print(get_mode) # {'orange': 2, 'apple': 3}
print(max(list(data .values()))) # output : 3 because maximum apple count is 3
# mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
# this list comprehension can be written like below
mode = [] # initailize a list
for k, v in get_mode.items(): # here k represents key, v reperents value
# k = orange, v = 2 | k=apple, v = 3
if v == max(list(data.values())):
# v = 2, max = 3 | v = 3, max = 3
mode.append(k) # append k(apple) to the mode list
print(mode) # ouput : ['apple'], create a list