gpt4 book ai didi

python - 如何形成 'any' 条件的相反语句?

转载 作者:行者123 更新时间:2023-11-28 21:31:07 25 4
gpt4 key购买 nike

我有以下有效的代码

[i for i in range(1, 16) if any(i % j == 0 for j in [3,5])]

其输出为[3, 5, 6, 9, 10, 12, 15],可以被 3 或 5 整除的数字。

但是,当我尝试

[i for i in range(1, 16) if any(i % j != 0 for j in [3,5])]

我明白了[1、2、3、4、5、6、7、8、9、10、11、12、13、14]

我正在寻找的是[1,2,4,7,8,11,13,14]

非常感谢!

最佳答案

您需要否定条件切换到全部:

>>> [i for i in range(1, 16) if <b>all</b>(i % j <b>!=</b> 0 for j in [3,5])]
[1, 2, 4, 7, 8, 11, 13, 14]

或者保持条件不变并否定any的结果:

>>> [i for i in range(1, 16) if <b>not</b> any(i % j == 0 for j in [3,5])]
[1, 2, 4, 7, 8, 11, 13, 14]

两者都可以源自 De Morgan's laws ,其中之一指出

not (A or B) == not A and not B

(概括为 not (A or B or ... ) == not A and not B and ...)。

any(Ai for i in ...) 相当于 A0 或 A1 或 A2 或 ... 或 An,并且 all(Ai for i in ...) 相当于 A0 和 A1 和 A2 或 ... 或 An

关于python - 如何形成 'any' 条件的相反语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com