List comprehension output is None [duplicate]

2020-05-10 02:47发布

问题:

I'm new to python and I wanted to try to use list comprehension but outcome I get is None.

print
wordlist = ['cat', 'dog', 'rabbit']
letterlist = []
letterlist = [letterlist.append(letter) for word in wordlist for letter in word if letter not in letterlist]
print letterlist

# output i get: [None, None, None, None, None, None, None, None, None]
# expected output: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

Why is that? It seems that it works somehow because I get expected number of outcomes (9) but all of them are None.

回答1:

list.append(element) doesn’t return anything – it appends an element to the list in-place.

Your code could be rewritten as:

wordlist = ['cat', 'dog', 'rabbit']
letterlist = [letter for word in wordlist for letter in word]
letterlist = list(set(letterlist))
print letterlist

… if you really want to use a list comprehension, or:

wordlist = ['cat', 'dog', 'rabbit']
letterset = set()
for word in wordlist:
    letterset.update(word)
print letterset

… which is arguably clearer. Both of these assume order doesn’t matter. If it does, you could use OrderedDict:

from collections import OrderedDict
letterlist = list(OrderedDict.fromkeys("".join(wordlist)).keys())
print letterlist


回答2:

list.append returns None. You need to adjust the expression in the list comprehension to return letters.

wordlist = ['cat', 'dog', 'rabbit']
letterset = set()
letterlist = [(letterset.add(letter), letter)[1]
              for word in wordlist
              for letter in word
              if letter not in letterset]
print letterlist


回答3:

If order doesn't matter, do this:

 resultlist = list({i for word in wordlist for i in word})