简体   繁体   中英

Nested list comprehension with enumerate build-in function

I studying list comprehension and I stuck in the following code:

[[c for c in enumerate(r)] for r in enumerate(['a','b','c'])]

which returns:

[[(0, 0), (1, 'a')], [(0, 1), (1, 'b')], [(0, 2), (1, 'c')]]

However, I was expecting this:

[[(0,(0,'a'))],[(1,(1,'b'))],[(2,(2,'c'))]]

I read some articles but could not understand the prompted output. Someone can explain it to me, please.

You are enumerating each individual element of the outer enumerate() :

  • You create one enumerate() over the list ['a', 'b', 'c'] , this produces a sequence of tuples with (counter, letter) .

  • You then apply enumerate() to each of the (counter, letter) tuples, producing (0, count) and (1, letter) tuples each .

So in the end you get the following element for each of the letters in the list ['a', 'b', 'c'] :

[
    [(0, 0), (1, 'a')],  # enumerate((0, 'a'))
    [(0, 1), (1, 'b')],  # enumerate((1, 'b'))
    [(0, 2), (1, 'c')],  # enumerate((2, 'c'))
]

If you wanted to get (counter, (counter, element)) , you need to apply enumerate() to the whole output of enumerate() , not to each individual tuple:

>>> [combo for combo in enumerate(enumerate(['a','b','c']))]
[(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]

You could just call list() on enumerate() too:

>>> list(enumerate(enumerate(['a','b','c'])))
[(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]

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