如何获得列表推导的索引值?

djq*_*djq 7 python dictionary list-comprehension list

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

{ p.id : {'total': p.total} for p in p_list}
Run Code Online (Sandbox Code Playgroud)

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

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

 c_list = [x for x in range(len(p_list))] 
Run Code Online (Sandbox Code Playgroud)

然后试着看看如何c也可以列出结果的一部分.我以为我需要这样的东西:

{ (p,c) for p in p_list for c in c_list} 
Run Code Online (Sandbox Code Playgroud)

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

{ (p.id, c : {'total': p.total, 'position': c}) for p in p_list for c in c_list}
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 10

使用enumerate获得指数,以及从可迭代的项目:

{ (p.id, ind) : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
Run Code Online (Sandbox Code Playgroud)

更新:

{ p.id : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
Run Code Online (Sandbox Code Playgroud)

帮助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]), ...
Run Code Online (Sandbox Code Playgroud)