从python中的列表创建位置映射字典

2024-04-27 02:50:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多单词的单子。在

从中,我想创建一个字典,其中包含列表中每个唯一的单词作为键,以及它在(列表索引)中出现的第一个位置作为键的值。在

有没有一种有效的方法来实现这一点?在


Tags: 方法列表字典单词单子
3条回答

因为你无论如何都要看每一个词,所以它不会比这个快:

index = {}

for position, word in enumerate(list_of_words):
    if word not in index:
        index[word] = position
>>> l = ['a', 'b', 'c', 'b', 'a', 'd']
>>> dic = {l[i]:i for i in range(len(l)-1,-1,-1)}
>>> print(dic)
{'a': 0, 'c': 2, 'b': 1, 'd': 5}
>>> l = ['a', 'b', 'c', 'b', 'a', 'd']
>>> import itertools as it
>>> dict(it.izip(reversed(l), reversed(xrange(len(l)))))
{'a': 0, 'b': 1, 'c': 2, 'd': 5}

相关问题 更多 >