python - 如何检查列表是否只有一个真实值?

标签 python

在 python 中,我有一个列表应该有 一个且只有一个真值(即 bool(value) 为真)。有没有聪明的方法来检查这个?现在,我只是遍历列表并手动检查:

def only1(l)
    true_found = False
    for v in l:
        if v and not true_found:
            true_found=True
        elif v and true_found:
             return False #"Too Many Trues"
    return true_found

这看起来不优雅,也不是很pythonic。有没有更聪明的方法来做到这一点?

最佳答案

不需要导入的:

def single_true(iterable):
    i = iter(iterable)
    return any(i) and not any(i)

或者,也许是更易读的版本:

def single_true(iterable):
    iterator = iter(iterable)

    # consume from "i" until first true or it's exhausted
    has_true = any(iterator) 

    # carry on consuming until another true value / exhausted
    has_another_true = any(iterator) 

    # True if exactly one true found
    return has_true and not has_another_true

这个:

  • 确保 i 具有任何真实值
  • 从可迭代的那个点开始查找,以确保没有其他真实值

关于python - 如何检查列表是否只有一个真实值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801322/

相关文章:

python - 将 url 正则表达式转换为 django 2.1 中的路径

python - 替换 Pandas 数据框中的单元格值

占用太多内存的对象的Python列表

python - 分析多个对象并返回 bool 值的函数的命名约定

python - 如何将 Telegram 聊天机器人中的内联键盘设置为 python-telegram-bot 中的其他功能?

python - 列表/元组元素的异或

python - 如何随机更改列表中的 bool 值

python - 在 pypi 上列出多个版本

python - 使用具有变量值的 pymongo 查询 mongoDb

python - Django - 以 10 为基数的 int() 的无效文字 python django