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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -