列表理解输出无
我是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),但所有人都不是。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
list.Append(element)
不返回任何内容 - 它将元素附加到就地列表。您的代码可以被重写为:
…如果您真的想使用列表理解,或者:
…可以说是更清楚的。这两个都假定顺序无关紧要。如果是这样,您可以使用OrderDict:
list.append(element)
doesn’t return anything – it appends an element to the list in-place.Your code could be rewritten as:
… if you really want to use a list comprehension, or:
… which is arguably clearer. Both of these assume order doesn’t matter. If it does, you could use OrderedDict:
list.Append
返回无
。您需要调整列表理解中的表达式以返回字母。list.append
returnsNone
. You need to adjust the expression in the list comprehension to return letters.如果订单没关系,请执行此操作:
If order doesn't matter, do this: