【问题标题】:python: dictionary comprehension with list index [duplicate]python:带有列表索引的字典理解[重复]
【发布时间】: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


【解决方案1】:
>>> LL = ["this","is","a","sample","list"]
>>> dict(enumerate(LL))
{0: 'this', 1: 'is', 2: 'a', 3: 'sample', 4: 'list'}

【讨论】:

  • 美丽。 Python 是最好的!此外,可以在特定值开始枚举,如建议的here
【解决方案2】:
inp = ["this","is","a","sample","list"]

print {idx: value for idx, value in enumerate(inp)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-27
    • 2020-04-18
    • 2019-02-15
    • 2015-03-31
    • 2011-06-02
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多