Python 如何在生成器中增加值

Python 如何在生成器中增加值,python,python-3.x,generator,yield,Python,Python 3.x,Generator,Yield,我希望在遍历~5GB文件的生成器中执行以下操作: from collections import Counter c=Counter() lines_as_list = (line.strip().split('|') for line in open('file-00000-of-00001.csv')) header = next(lines_as_list) item_data = (dict(zip(header, data)) for data in lines_as_list) to

我希望在遍历~5GB文件的生成器中执行以下操作:

from collections import Counter
c=Counter()
lines_as_list = (line.strip().split('|') for line in open('file-00000-of-00001.csv'))
header = next(lines_as_list)
item_data = (dict(zip(header, data)) for data in lines_as_list)
totals_per_country = (c[item['country']]+=1 for item in item_data)
这当然失败了,因为试图在理解中分配一个值。在不使用for循环或库(如pandas)的情况下,在生成器中执行此操作的建议方法是什么。

将计数器创建为


现在,您的国家已经统计完毕。

一种方法是将国家的生成器传递给计数器,因为这需要一个iterable。例如:

>>> countries = (item['country'] for item in item_data)
>>> totals_per_country = Counter(countries) # not a generator, evaluates immediately
>>> totals_per_country.most_common(5)
[('US', 299072), ('CA', 183927), ('GB', 150242), ('AU', 131295), ('DE', 100611)]

在Python 3.8中使用新的Walrus运算符

c[项目['country']]:=c[项目['country']]+1,用于项目_数据中的项目 这允许您对表达式进行赋值,使其在其他地方(如理解)在语法上合法

>>> countries = (item['country'] for item in item_data)
>>> totals_per_country = Counter(countries) # not a generator, evaluates immediately
>>> totals_per_country.most_common(5)
[('US', 299072), ('CA', 183927), ('GB', 150242), ('AU', 131295), ('DE', 100611)]