4

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.

1
  • 2
    SO is not a code-writing service. We expect you to show us what you've tried and a specific problem that you're having. "I want a program that does this, can somebody write it for me" is not an appropriate question for this site. Commented Dec 22, 2017 at 18:27

3 Answers 3

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

Should work.

Sign up to request clarification or add additional context in comments.

1 Comment

This works thanks man i couldn't figure out the syntax for using two loops in a list comprehension
3

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]

Comments

0

You can try this:

s = [len(i) for a, b in fourier_dict.items() for i in b]

1 Comment

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().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.