我有以下几点:
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.
更多推荐
发布评论