我正在尝试在列表理解中编写代码。但是,当我这样做时,我收到了 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"]
3 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
list.remove就地更改列表并返回 None。例如:
a = ["I", "have", "something", "to", "buy"]
print(a.remove("I")) # ['have', 'something', 'to', 'buy']
print(a) # None
如果你真的想在一行中做到这一点,你可以保留你的代码。虽然您不需要 aa,但只需打印 a。
慕运维8079593
TA贡献1876条经验 获得超5个赞
您需要使用理解 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']
跃然一笑
TA贡献1826条经验 获得超6个赞
尝试打印(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)
添加回答
举报
0/150
提交
取消