How to frame two for loops in list comprehension python

后端 未结 6 2130
予麋鹿
予麋鹿 2020-11-28 20:06

I have two lists as below

tags = [u\'man\', u\'you\', u\'are\', u\'awesome\']
entries = [[u\'man\', u\'thats\'],[ u\'right\',u\'awesome\']]

6条回答
  •  野性不改
    2020-11-28 20:12

    In comprehension, the nested lists iteration should follow the same order than the equivalent imbricated for loops.

    To understand, we will take a simple example from NLP. You want to create a list of all words from a list of sentences where each sentence is a list of words.

    >>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
    >>> all_words = [word for sentence in list_of_sentences for word in sentence]
    >>> all_words
    ['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']
    

    To remove the repeated words, you can use a set {} instead of a list []

    >>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
    >>> all_unique_words
    ['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']
    

    or apply list(set(all_words))

    >>> all_unique_words = list(set(all_words))
    ['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']
    

提交回复
热议问题