python:具有列表索引的词典理解
我想用一个包含列表中某个值的索引位置的键创建字典。我正在使用python 2.7。以我的尝试为例:python:具有列表索引的词典理解,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我想用一个包含列表中某个值的索引位置的键创建字典。我正在使用python 2.7。以我的尝试为例: LL = ["this","is","a","sample","list"] LL_lookup = {LL.index(l):l for (LL.index(l), l) in LL} # desired output print LL_lookup[1] >> is 我认识到在这个例子中字典是不必要的-LL[1]将产生相同的结果。尽管如此,我们可以想象这样一种情况:1)给定一个
LL = ["this","is","a","sample","list"]
LL_lookup = {LL.index(l):l for (LL.index(l), l) in LL}
# desired output
print LL_lookup[1]
>> is
我认识到在这个例子中字典是不必要的-
LL[1]
将产生相同的结果。尽管如此,我们可以想象这样一种情况:1)给定一个更复杂的示例,字典更可取;2)字典查找可能会通过大量迭代产生边际性能增益 注意.index
不可靠,它返回项目的第一个索引,因此无法对重复的元素正常工作。index不可靠,它返回项目的第一个索引,因此无法对重复的元素正常工作。最好是Python!此外,还可以在特定值(如建议的值)处启动枚举。最好是Python!此外,还可以按建议的特定值启动枚举
>>> LL = ["this","is","a","sample","list"]
>>> dict(enumerate(LL))
{0: 'this', 1: 'is', 2: 'a', 3: 'sample', 4: 'list'}
inp = ["this","is","a","sample","list"]
print {idx: value for idx, value in enumerate(inp)}