[英]How can I get the index value of a list comprehension?
使用以下方法,我可以創建值的字典:
{ 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}
使用enumerate
來獲取索引以及iterable中的項:
{ (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]), ...
嘗試使用enumerate
。 它是一個生成器函數,它返回以下形式的元組:(i,iterable [i])。
{ p.id : {'id': p.id, 'position': i} for i, p in enumerate(p_list)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.