解释对字典的列表理解?

时间:2019-10-08 04:43:42

标签: python python-3.x

data = Counter(list_name) 
get_mode = dict(data) 
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] 

有人可以逐步解释第三行吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

如果v等于data字典值中的最大值,则返回get_mode中所有键的列表,其中v是该键的值输入字典

注意:dataget_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