在一行中构建 for 循环并收到错误的输出,即 Nonetype

我正在尝试在列表理解中编写代码。但是,当我这样做时,我收到了 nonetype。


代码:


a = ["I", "have", "something", "to", "buy"]

delete = ["I", "have"]


aa = [a.remove(x) for x in delete]

print(aa)

输出:


[None, None]

预期输出:


["something", "to", "buy"]


偶然的你
浏览 215回答 3
3回答

凤凰求蛊

list.remove就地更改列表并返回 None。例如:a = ["I", "have", "something", "to", "buy"]print(a.remove("I")) # ['have', 'something', 'to', 'buy']print(a) # None如果你真的想在一行中做到这一点,你可以保留你的代码。虽然您不需要 aa,但只需打印 a。

慕运维8079593

您需要使用理解 if 子句,例如:代码:aa = [x for x in a if x not in delete]测试代码:a = ["I", "have", "something", "to", "buy"]delete = ["I", "have"]aa = [x for x in a if x not in delete]print(aa)结果:['something', 'to', 'buy']

跃然一笑

尝试打印(a)而不是打印(aa)当您执行 a.remove(x) 时,它会将其从数组 'a' 中删除。  a = ["I", "have", "something", "to", "buy"]  delete = ["I", "have"]  aa = [a.remove(x) for x in delete]  print(a)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python