如果条件不为真,我试图让单行生成器表达式不执行任何操作

乘风 python 199

原文标题I am trying to get the one line generator expression to do nothing if the condition is not True

这是我的代码,我试图使用生成器表达式减去两个列表,但如果不满足条件,我无法让生成器表达式什么都不做。

ab=[1,2,2,3,4,5]
b=[3,4,5]
[ a if a in list(set(ab)-set(b)) else (nothing) for a in ab]

我希望生成器表达式返回[1,2,2]

原文链接:https://stackoverflow.com//questions/71463254/i-am-trying-to-get-the-one-line-generator-expression-to-do-nothing-if-the-condit

回复

我来回复
  • VPfB的头像
    VPfB 评论

    我想你想要这个(ab中没有的项目列表b

    [x for x in ab if x not in b]
    
    2年前 0条评论