首页 > 解决方案 > 使用 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

解决方案


我猜香草 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])

推荐阅读