【问题标题】:Get True if all values are False and get False if there is at least one True value python [closed]如果所有值都为 False,则为 True,如果至少有一个 True 值,则为 False python [关闭]
【发布时间】:2021-02-21 22:51:40
【问题描述】:

我想知道如何才能做到这一点。 我有一个这样的列表:

lst = [False, False, False]

如果所有元素都是False,我想获得True,并且如果列表在lst=[False, True, False] 的位置上至少有一个True 元素,我想获得False

我知道可以使用 any()all() 完成,但我无法获得我想要的解决方案。

我是这样开始的:

if not any(lst)
   print("something")

我已阅读 this 和一些链接,但没有得到预期的解决方案。

希望不要为这个问题而烦恼。感谢您阅读我。

【问题讨论】:

  • not any(lst) 有效。我不知道你的问题是什么。
  • 请提供预期的MRE。我们应该能够将您的代码块粘贴到文件中,运行它并重现您的问题。您发布的代码没有显示问题。

标签: python list


【解决方案1】:

使用一组:

>>> lst1 = [False, False, False]
>>> lst2 = [False, False, True]
>>> set(lst1)=={False}
True
>>> set(lst2)=={False}
False

或否定in

>>> not(True in lst1)
True
>>> not(True in lst2)
False

或否定any

>>> not(any(lst1))
True
>>> not(any(lst2))
False

这些方法都假设您的列表仅由TrueFalse 组成。如果你想测试,使用all:

>>> all(e in {True,False} for e in lst1)
True
>>> all(e in {True,False} for e in lst2)
True

或者再次使用集合:

>>> set(lst1)<={True,False}
True
>>> set(lst2)<={True,False}
True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2017-10-25
    • 2020-12-10
    • 1970-01-01
    相关资源
    最近更新 更多