首页 > 解决方案 > 带作业的列表理解

问题描述

我是 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 文档后我不知道如何将其转换为列表理解。

标签: 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])

推荐阅读