【问题标题】:Squeeze in an entry to a dictionary while creating the latter with enumerate function在使用枚举函数创建字典时挤压字典条目
【发布时间】:2017-07-16 10:16:22
【问题描述】:

有没有办法在一行上写下以下内容?

x = {item: i for i, item in enumerate([letters for letters in ascii_lowercase])}
x[' '] = 27

我尝试了类似的东西

x = {item: i for i, item in enumerate([letters for letters in ascii_lowercase]), ' ': 27}

但没有运气。

【问题讨论】:

    标签: python dictionary list-comprehension enumerate dict-comprehension


    【解决方案1】:

    Python >=3.5 使用 dict 扩展的解决方案

    x = {**{item: i for i, item in enumerate(ascii_lowercase)}, **{' ' : 27}}
    

    话虽如此,您的解决方案非常易读,我更喜欢它。但这是您尝试过的最接近的方法。

    【讨论】:

      【解决方案2】:

      假设 ascii_lowercase 来自内置的字符串模块,你会这样做:

      {item: i for i, item in enumerate(ascii_lowercase + ' ')}
      

      但是索引序列应该从 0 开始还是从 1 开始呢?您可以通过enumeratestart 参数来控制它(默认值为0)。

      如果序列必须是从 0 开始的并且你需要跳过索引 26,你需要做类似的事情

      {item: i for i, item in (*enumerate(ascii_lowercase), (27, ' '))}
      

      【讨论】:

        猜你喜欢
        • 2013-09-02
        • 1970-01-01
        • 2015-12-24
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        相关资源
        最近更新 更多