python - Nested list comprehension with enumerate build-in function -
i studying list comprehension , stuck in following code:
[[c c in enumerate(r)] r in enumerate(['a','b','c'])]
which returns:
[[(0, 0), (1, 'a')], [(0, 1), (1, 'b')], [(0, 2), (1, 'c')]]
however, expecting this:
[[(0,(0,'a'))],[(1,(1,'b'))],[(2,(2,'c'))]]
i read articles not understand prompted output. can explain me, please.
you enumerating each individual element of outer enumerate()
:
you create 1
enumerate()
on list['a', 'b', 'c']
, produces sequence of tuples(counter, letter)
.you apply
enumerate()
each of(counter, letter)
tuples, producing(0, count)
,(1, letter)
tuples each.
so in end following element each of letters in 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 wanted (counter, (counter, element))
, need apply enumerate()
whole output of enumerate()
, not each individual tuple:
>>> [combo combo in enumerate(enumerate(['a','b','c']))] [(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]
you call list()
on enumerate()
too:
>>> list(enumerate(enumerate(['a','b','c']))) [(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]
Comments
Post a Comment