简体   繁体   中英

How can I get the index value of a list comprehension?

Using the following approach I am able to create a dictionary of values:

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

This results in {34:{'total':334}, 53:{'total: 123} ... }

I would also like to list an index from the list so that I know which position p.id was in. I made a list like this:

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

And then tried to see how c could also be listed as part of the result. I thought I needed something like this:

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

but when I tried to implement it, I could not get c to be a value in the dictionary:

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

Use enumerate to get index as well as the item from the iterable:

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

Update:

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

Help on 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]), ...

Try using enumerate . It's a generator function that returns tuples of the form: (i, iterable[i]).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM