mercredi 2 octobre 2019

List comprehension with nested loops and if condition, and membership to the new list

Here is my regular nested loop with if condition, and membership to the new list:

wordlist = ["micro", "macro", "stats"]
letterlist = []

for aword in wordlist:
    for aletter in aword:
        if aletter not in letterlist:  
            letterlist.append(aletter)
print(letterlist)

Which prints out the letters without duplicates: ['m', 'i', 'c', 'r', 'o', 'a', 's', 't']

When I try to do the same using list comprehension, I can only get through the nested loops:

wordlist = ["micro", "macro", "stats"]
letterlist = [aletter for aword in wordlist for aletter in aword]
print(letterlist)

This prints all letters with duplicates: ['m', 'i', 'c', 'r', 'o', 'm', 'a', 'c', 'r', 'o', 's', 't', 'a', 't', 's']

This does not work unfortunately:

wordlist = ["micro", "macro", "stats"]
letterlist = [[if aletter not in letterlist] for aword in wordlist for aletter in aword]

Question: How do I perform the perform the nestloop with if statement using list comprehension based on my above example?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire