python - 带作业的列表理解
问题描述
我是 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])
推荐阅读
- html - html中的水平菜单显示错误,同时删除css中的float属性
- html - 在桌面上并排显示 2 个 div 和 2nd div 下的 3rd div 并在移动屏幕上显示 1st 和 2nd div 下的 3rd div
- jenkins - 在 Jenkins 脚本外壳中屏蔽凭据
- r - 将线或箭头附加到 R 中的数据标签
- r - 如何将没有固定值的底图添加到文档中
- r - 如何在一个(或拆分的)pdf中可视化多个条形图
- mongodb - 查询日期超过 10 天
- javascript - 具有区域设置格式的十进制/浮点输入字段
- python-3.x - 如何为文本构建马尔可夫模型?
- fix-protocol - FIX 数据字典的起源