Search code examples
pythonlistlist-comprehensionnested-for-loop

Converting A Nested For Loop Into a List Comprehension


I am trying to write a nested list comp for this nested for loop and I can't find a solution for one that also contains a tracker variable so any help is appreciated.

So the story is I have a dictionary with single words as keys and a list of sentences as values and I'm accessing each list, then each sentence in the list, splitting it on whitespace, and storing the cumulative token count across each sentence in a new list, and finally resetting the count and moving to the next list.

# combines the sum of each sentence
l = []

# Tracker variable
sum_len = 0

# For each list in the dictionary values
for cl in word_freq.values():

    # For each sentence in the current list
    for sen in cl:

      # split into tokens and combine the sum of each sentence
      sum_len += len(sen.split())

    # Append the sum of tokens  
    l.append(sum_len)

    # Reset the variable
    sum_len = 0

Solution

  • If you want to create a list of word count from a dictionary, you can do:

    l = [sum(len(sen.split()) for sen in v) for v in word_freq.values()]