[英]Appending to a list inside of a dictionary
我正在浏览各个单词的列表,并创建一个词典,其中单词是键,而单词的索引是值。
dictionary = {}
for x in wordlist:
dictionary[x] = wordlist.index(x)
目前,这可以正常工作,但是我希望在第二次或第三次发现相同单词时添加更多索引。因此,如果该短语是“我要去城镇”,我将寻找创建一个这样的字典:
{'I': 0, 'am' : 1, 'going' : 2, 'to': (3, 5), 'go' : 4, 'town' : 6}
所以我想在字典中需要列表吗? 然后向它们附加更多索引? 关于如何实现这一目标的任何建议都将是很棒的!
您可以这样做:
dictionary = {}
for i, x in enumerate(wordlist):
dictionary.setdefault(x, []).append(i)
说明:
index()
。 使用enumerate()
更高效,更酷。 dict.setdefault()
使用第一个参数作为键。 如果找不到,则插入第二个参数,否则将忽略它。 然后,它返回(可能是新插入的)值。 list.append()
将项目追加到列表中。 您将获得如下内容:
{'I': [0], 'am' : [1], 'going' : [2], 'to': [3, 5], 'go' : [4], 'town' : [6]}
使用列表而不是元组,并使用列表,即使它只是一个元素。 我真的认为这样更好。
更新 :
@millimoose对OP的评论无耻地启发了(谢谢!),这段代码更好,更快,因为它并没有建立很多从未插入到字典中的[]
:
import collections
dictionary = collections.defaultdict(list)
for i, x in enumerate(wordlist):
dictionary[x].append(i)
>>> wl = ['I', 'am', 'going', 'to', 'go', 'to', 'town']
>>> {w: [i for i, x in enumerate(wl) if x == w] for w in wl}
{'town': [6], 'I': [0], 'am': [1], 'to': [3, 5], 'going': [2], 'go': [4]}
对象是对象,无论它们在哪里。
dictionary[x] = []
...
dictionary[x].append(y)
可能的解决方案:
dictionary= {}
for i, x in enumerate(wordlist):
if not x in dictionary : dictionary[x]= []
dictionary[x].append( i )
import collections
dictionary= collections.defaultdict(list)
for i, x in enumerate( wordlist ) :
dictionary[x].append( i )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.