列表理解输出为None

时间:2016-01-02 10:57:03

标签: python list python-2.7 list-comprehension

我是python的新手,我想尝试使用列表理解,但我得到的结果是无。

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']

为什么?它似乎以某种方式起作用,因为我得到了预期的结果数(9),但它们都是无。

3 个答案:

答案 0 :(得分:2)

list.append(element)不会返回任何内容 - 它会在列表中附加一个元素。

您的代码可以重写为:

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

...如果你真的想使用列表理解,或者:

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

......这可以说是更清楚了。这两个假设顺序无关紧要。如果是,您可以使用OrderedDict:

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

答案 1 :(得分:1)

list.append返回None。您需要调整列表推导中的表达式以返回字母。

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

答案 2 :(得分:0)

如果订单无关紧要,请执行以下操作:

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