Python:用于实例数量的字典列表理解(Python: dictionary list comprehension for count of number of instances)

编程入门 行业动态 更新时间:2024-10-13 10:28:00
Python:用于实例数量的字典列表理解(Python: dictionary list comprehension for count of number of instances)

我有以下几点:

a = rand(100).round() #for example count = {} for i in a: count[i] = count.get(i, 0) + 1 # print(a) print(count)

最后一行返回类似{0.0: 52, 1.0: 48}

我想做for循环作为词典理解。 但,

count = {i: count.get(i,0)+1 for i in a}

总是返回{0.0: 1, 1.0: 1}

我究竟做错了什么?

I have the following:

a = rand(100).round() #for example count = {} for i in a: count[i] = count.get(i, 0) + 1 # print(a) print(count)

The last line returns something like {0.0: 52, 1.0: 48}

I would like to do the for loop as dictionary comprehension. But,

count = {i: count.get(i,0)+1 for i in a}

always returns {0.0: 1, 1.0: 1}

What am I doing wrong?

最满意答案

该声明

count = {i: count.get(i,0)+1 for i in a}

由两部分组成:

{i: count.get(i,0)+1 for i in a}

count = ...

第一个计算字典,当计算它时, count只是您首先定义的空字典,与理解表达式构造的字典没有关系。

只有在字典构造结束时,才将其分配给count (替换空的字典)。 在理解评估期间, count值为空并保持为空,因此每个get将始终返回默认值0。

无法在理解中使用的表达式中引用理解中构造的对象(例如列表或字典)。

The statement

count = {i: count.get(i,0)+1 for i in a}

is composed of two parts:

{i: count.get(i,0)+1 for i in a}

and

count = ...

the first one computes a dictionary and when evaluating it count is just the empty dictionary you defined first and has no relation with the dictionary being constructed by the comprehension expression.

Only at the end of the dictionary construction this is assigned to count (replacing the empty dictionary). During the comprehension evaluation count is empty and remains empty so every get will always return the default value of 0.

There is no way to refer to the object being constructed in a comprehension (e.g a list or a dictionary) in the expressions used inside the comprehension.

更多推荐

本文发布于:2023-07-30 15:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   实例   数量   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!