python - 使用 lambda 创建字典(内部的增量计数器)
问题描述
我是python的新手。我有这个程序:
wordlist = ['pea', 'rpai', 'rpai', 'schiai', 'pea', 'rpe', 'zoi', 'zoi', 'briai', 'rpe']
dictionary = {}
counter = 0
result = list(map(lambda x: dictionary[wordlist[x]] = dictionary.get(wordlist[x], counter +=1), wordlist))
print(result)
结果必须是:
result = [0, 1, 1, 2, 0, 3, 4, 4, 5, 3]
我所要做的是将列表中的所有元素(作为键)附加到字典中,并将增量计数器作为键的值。使用此代码,我得到“lambda 不能包含分配。我该怎么做?谢谢!
编辑解释:
使用字符串列表,我必须创建一个字典,其中 str 列表的元素作为“参数”,值作为“键”
该值是这样计算的:列表的第一个元素是 0。如果它是一个从未出现过的新字符串(唯一),则后面的元素具有最后一个值(在这种情况下为 0)=+1。相反,如果新元素是重复的字符串(字典中已经有一个),则它采用与第一个相同的原始值。
字典将是:
{'pea': 0, 'rpai': 1, 'rpai': 1, 'schiai': 2, 'pea': 0, 'rpe': 3,
'zoi': 4, 'zoi': 4, 'briai': 5,'rpe': 3}
而结果与列表将是:
[0, 1, 1, 2, 0, 3, 4, 4, 5, 3]
解决方案
我猜香草 Python 最简单的解决方案是使用defaultdict:
from collections import defaultdict
wordlist = ["pea","rpai","rpai","schiai","pea","rpe", "zoi","zoi","briai","rpe"]
vocab = defaultdict(lambda: len(vocab))
# result will be [0, 1, 1, 2, 0, 3, 4, 4, 5, 3]
result = [vocab[word] for word in wordlist]
更详细的等价物,导致相同的结果:
vocab = {}
result = []
for word in wordlist:
if word not in vocab:
vocab[word] = len(vocab)
result.append(vocab[word])
推荐阅读
- javascript - 通过 AJAX 加载的元素上的选择器
- python - 多处理 - 如何使用键盘中断取消进程?
- tokenize - 如何使用 BertTokenizer 加载 Tokenizer 模型?
- python - 数据框未插入数据库但抛出 DPI 未连接错误
- powershell - PowerShell 7 中加载的默认程序集是什么
- apache - Apache 虚拟主机语法
- typescript - 用于分析的屏幕跟踪中 React Navigation v5 中 routeNameRef 的 Typescript 类型
- html - 我想使用 thymeleaf 模板引擎在属性文件中显示文本
- c - 在 Eclipse 中运行简单的 hello world 程序 C 时出错
- oracle - 操作从内部查询传递的外部查询中的结果集