How to convert a nested loop to a list comprehension in python

12,266

Solution 1

max_len = [len(occur) for word in fourier_dict for occur in fourier_dict[word]]

Should work.

Solution 2

So first off, you don't actually use the key of the dict, so you can simplify to:

max_len = []
for word in fourier_dict.values():
    for occur in word:
        max_len.append(len(occur))

directly iterating the values (use .itervalues() if it's Py2 code to avoid a temporary list). From there, it's a simple transform to a listcomp, the value to "append" is on the far left, while the loops are laid out left to right, from outer-most to inner-most:

max_len = [len(occur) for word in fourier_dict.values() for occur in word]
Share:
12,266
Alien128
Author by

Alien128

Updated on June 04, 2022

Comments

  • Alien128
    Alien128 almost 2 years

    How can i convert this code to list comprehension in python

    max_len = []
    for word in fourier_dict:
        word = fourier_dict[word]
        for occur in word:
            max_len.append(len(occur))
    

    Im new to python and i have to convert this nested loop to a list comprehension which i cant figure out. A little help would be really appreciated.

  • ShadowRanger
    ShadowRanger over 6 years
    Your loops are backwards; you iterate b before b exists. You also never use a, so you may as well just use .values() over .items().
  • Alien128
    Alien128 over 6 years
    This works thanks man i couldn't figure out the syntax for using two loops in a list comprehension