【发布时间】:2013-05-28 05:48:09
【问题描述】:
我想创建一个字典,其中的键包含列表中某个值的索引位置。我正在使用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)给定一个更复杂的例子,字典更可取,b)字典查找可能会通过大量迭代产生边际性能增益。
【问题讨论】:
-
注意
.index不可靠,它返回项目的第一个索引,因此对于重复元素无法正常工作
标签: python python-2.7 dictionary