列表推导输出为“无" [英] List comprehension output is None

查看:103
本文介绍了列表推导输出为“无"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

那是为什么?看来它能以某种方式起作用是因为我得到了预期的结果数(9),但所有结果都不是.

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

推荐答案

list.append(element)不返回任何内容-它将元素原位添加到列表中.

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

您的代码可以重写为:

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

…可以说更清晰.两者都假定顺序无关紧要.如果可以,则可以使用OrderedDict:

… 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

这篇关于列表推导输出为“无"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆