Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python计数器的行为是否应如下所示?_Python_Python 3.x_List_Python 2.7 - Fatal编程技术网

python计数器的行为是否应如下所示?

python计数器的行为是否应如下所示?,python,python-3.x,list,python-2.7,Python,Python 3.x,List,Python 2.7,我有一个字典清单如下 [ {'sex': 2, 'newspaper_sheet__country': 'ML', 'n': 7}, {'sex': 1, 'newspaper_sheet__country': 'ML', 'n': 5}, {'sex': 2, 'newspaper_sheet__country': 'ML', 'n': 10} ] 然后我有两个计数器 from collections import Counter counts = Counter(

我有一个字典清单如下

[
    {'sex': 2, 'newspaper_sheet__country': 'ML', 'n': 7},
    {'sex': 1, 'newspaper_sheet__country': 'ML', 'n': 5},
    {'sex': 2, 'newspaper_sheet__country': 'ML', 'n': 10}
]
然后我有两个计数器

from collections import Counter

counts = Counter()
counts1 = Counter()
我正在以以下格式更新这两个计数器

for row in rows:
    counts.update({(row['sex'], row['newspaper_sheet__country']): row['n']})

我希望这两个计数的值是相同的,因为唯一的区别是1使用for循环,而另一个使用dict循环


为什么这两个值不同?

通过调用
计数器。更新
for
循环的每次迭代中,
计数器
对象将使用每次调用的输入dict进行更新


通过dict理解,键值首先聚合到dict中,然后再传递到
计数器。更新
。由于dict理解中复制键的后一个值将覆盖相同键的前一个值,因此键的值
10
(2,'ML')
覆盖相同键的值
7
,导致
计数器
对象最终没有考虑值
7

因为在这样的循环中调用
.update
并不等同于传递字典理解的结果,看看字典理解创建了什么:

>>> rows = [
...     {'sex': 2, 'newspaper_sheet__country': 'ML', 'n': 7},
...     {'sex': 1, 'newspaper_sheet__country': 'ML', 'n': 5},
...     {'sex': 2, 'newspaper_sheet__country': 'ML', 'n': 10}
... ]
>>> {(row['sex'], row['newspaper_sheet__country']): row['n'] for row in rows}
{(2, 'ML'): 10, (1, 'ML'): 5}

字典有唯一的键,最后一个看到的项会被保留。

区别在于
update()
使用列表理解的方式

对于基于for循环的方法,计数器每次都会更新,并聚合匹配键的计数,但是对于列表理解方法,它只会获得一个具有唯一键的字典

列表理解方法可细分为:

dic = {(row['sex'], row['newspaper_sheet__country']): row['n'] for row in rows}
print(dic)  # dic only contains unique key value pairs here
counts1.update(dic)
因此,
counts1
只更新一次,而由于基于循环的方法,
counts
会更新多次

dic = {(row['sex'], row['newspaper_sheet__country']): row['n'] for row in rows}
print(dic)  # dic only contains unique key value pairs here
counts1.update(dic)