[英]List comprehension with assignments
I'm new to Python and I try to convert this: 我是Python的新手,我尝试将其转换为:
for source in data['Source']:
for index in range(len(source)):
if source == sources[index]:
percent[index] += 1
pass
to this: 对此:
sources = [percent[index]+=1 for source in data['Source'] for index in range(len(source)) if source == sources[index]]
but I give an error E0001
, after reading Python documentation I don't know how to convert this to a list comprehension. 但是我给出了错误E0001
,在阅读Python文档之后,我不知道如何将其转换为列表理解。
Assignments are statements, which are not allowed in list comprehensions, which support only expressions. 赋值是语句,在列表推导中是不允许的,它仅支持表达式。
You can use sum
instead: 您可以使用sum
代替:
sources = {index: sum(1 for index in range(len(source)) if source == sources[index]) for source in data['Source']}
A more efficient method would be to use collections.Counter
, as @Amadan has suggested in the comments: 一种更有效的方法是使用collections.Counter
,就像@Amadan在评论中建议的那样:
import collections.Counter:
sources = Counter(index for source in data['Source'] for index in range(len(source)) if source == sources[index])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.