Home > Mobile >  I am struggling with understanding the following list comprehension
I am struggling with understanding the following list comprehension

Time:10-19

Can please someone write the following list comprehension in simple for loops and statements.

new_words = ' '.join([word for word in line.split() if not 
any([phrase in word for phrase in char_list])])

I wrote the above list comprehension in the following code but it doesn't work.

new_list = []
for line in in_list:
  for word in line.split():
    for phrase in char_list:  
        if not phrase in word:
          new_list.append(word)
return new_list

Thanks

CodePudding user response:

new_words = ' '.join(
    [
        word for word in line.split() 
        if not any(
            [phrase in word for phrase in char_list]
        )
    ]
)

is more or less equivalent to this:

new_list = []
for word in line.split():
    phrases_in_word = []
    for phrase in char_list:
        # (phrase in word) returns a boolean True or False
        phrases_in_word.append(phrase in word)  
     
    if not any(phrases_in_word):
        new_list.append(word)

new_words = ' '.join(new_list)

CodePudding user response:

new_words = ' '.join([word for word in line.split() 
                      if not any([phrase in word for phrase in char_list])])

is the equivalent of:

lst = []
for word in line.split(): 
    for phrase in char_list: 
        if phrase in word:
            break
    else:  # word not in ANY phrase
        lst.append(word)
new_words = ' '.join(lst)
  • Related