【问题标题】:How can I get the index value of a list comprehension?如何获取列表理解的索引值?
【发布时间】:2013-09-19 21:52:03
【问题描述】:

使用以下方法,我可以创建一个值字典:

{ p.id : {'total': p.total} for p in p_list}

这导致{34:{'total':334}, 53:{'total: 123} ... }

我还想从列表中列出一个索引,以便我知道p.id 在哪个位置。我做了一个这样的列表:

 c_list = [x for x in range(len(p_list))] 

然后尝试查看c 如何也可以作为结果的一部分列出。我想我需要这样的东西:

{ (p,c) for p in p_list for c in c_list} 

但是当我尝试实现它时,我无法让 c 成为字典中的值:

{ (p.id, c : {'total': p.total, 'position': c}) for p in p_list for c in c_list}

【问题讨论】:

    标签: python list dictionary list-comprehension


    【解决方案1】:

    使用enumerate 从可迭代对象中获取索引以及项目:

    { (p.id, ind) : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
    

    更新:

    { p.id : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
    

    求助enumerate:

    >>> print enumerate.__doc__
    enumerate(iterable[, start]) -> iterator for index, value of iterable
    
    Return an enumerate object.  iterable must be another object that supports
    iteration.  The enumerate object yields pairs containing a count (from
    start, which defaults to zero) and a value yielded by the iterable argument.
    enumerate is useful for obtaining an indexed list:
        (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
    

    【讨论】:

    • 感谢您的回答。如果我尝试这个,我会收到 keys must be a string 错误。我认为这是因为它试图使用(p.id, ind) 作为字典的键值;我不知道如何避免它。
    • @celenius 对我来说很好,元组是字典的有效键。
    • 但是如果你知道索引,为什么要查询字典(使用索引作为元组键的一部分)来获取索引? :P 这是我的问题。
    • @ShashankGupta 抱歉 - 这是一个错字。我试图将第一个值作为键字典,我想(p.id, ind)[0] 会起作用吗?
    • @celenius 只需使用:p.id: {'id': p.id, 'position': ind},如果您只想将 p.id 作为键。
    【解决方案2】:

    尝试使用enumerate。它是一个生成器函数,它返回以下形式的元组:(i, iterable[i])。

    { p.id : {'id': p.id, 'position': i} for i, p in enumerate(p_list)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多