[英]List comprehension with assignments
我是Python的新手,我嘗試將其轉換為:
for source in data['Source']:
for index in range(len(source)):
if source == sources[index]:
percent[index] += 1
pass
對此:
sources = [percent[index]+=1 for source in data['Source'] for index in range(len(source)) if source == sources[index]]
但是我給出了錯誤E0001
,在閱讀Python文檔之后,我不知道如何將其轉換為列表理解。
賦值是語句,在列表推導中是不允許的,它僅支持表達式。
您可以使用sum
代替:
sources = {index: sum(1 for index in range(len(source)) if source == sources[index]) for source in data['Source']}
一種更有效的方法是使用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.