简体   繁体   English

理解python中的计数器和字典理解

[英]Understanding counter and dictionary comprehensions in python

I have tried to find an explanation but couldn't, so my apologies if this is a silly question.我试图找到一个解释但找不到,所以如果这是一个愚蠢的问题,我很抱歉。

Having data x:有数据 x:

 x = [(1, {'gender': 'male'}),
      (2, {'gender': 'female'}),
      (3, {'gender': 'male'}),
      (4, {'gender': 'female'}),
      (5, {'gender': 'male'})]
      ...

A plausible solution for counting the occurrences of each gender would be:计算每个性别的出现次数的合理解决方案是:

from collections import Counter
Counter([d['gender'] for n, d in x)])

Returning:返回:

Counter({'female':2, 'male':3})

Now I am trying to understand how "d['gender'] for n, d " works within "Counter([d['gender'] for n, d in x)]".现在我试图了解“d['gender'] for n, d”如何在“Counter([d['gender'] for n, d in x)]”中工作。 What exactly is "n" in this case?在这种情况下,“n”究竟是什么?

Many thanks for any pointers.非常感谢您的指点。

x is a list, so for <whatever> in x iterates through x and assigns each element to <whatever> . x是一个列表,因此for <whatever> in x x中的for <whatever> in x遍历x并将每个元素分配给<whatever>

The elements of x are tuples, so you can use tuple assignment to assign each item in the tuple to a different variable. x的元素是元组,因此您可以使用元组赋值将元组中的每个项目分配给不同的变量。 for n, d in x means that n is assigned the first item in the tuple, and d is assigned the second item. for n, d in x表示n被赋予元组中的第一项,而d被赋予第二项。

So the first iteration does所以第一次迭代

n, d = (1, {'gender': 'male'})

This sets n = 1 and d = {'gender': 'male'} .这设置n = 1d = {'gender': 'male'}

the next iteration does下一次迭代

n, d = (2, {'gender': 'female'})

This sets n = 2 and d = {'gender': 'female'} .这将设置n = 2d = {'gender': 'female'} And so on through the entire list.依此类推整个列表。

Finally, the list comprehension returns a list of d['gender'] , which is the gender element from the dictionaries.最后,列表推导返回一个d['gender']列表,它是字典中的gender元素。

n is not used, it was just needed as a placeholder so that d could be assigned to the second item in the tuples. n没有使用,它只需要作为占位符,以便d可以分配给元组中的第二项。 It could also have been written as:也可以写成:

[el[1]['gender'] for el in x]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM