Python - 评估列表子集的元素

标签 python list python-2.7

我有一个包含 bool 值的列表:

my_list = [False, False, False, True, True, True]

我想评估对于具有 (start, end) 索引的给定元组,列表是否包含 True 值,例如

contains_true(my_list, (0,0)) => False
contains_true(my_list, (0,2)) => False
contains_true(my_list, (0,3)) => True
contains_true(my_list, (3,5)) => True
contains_true(my_list, (5,5)) => True

目前我正在这样做:

def contains_true(my_list, indexes_tuple):
    start = indexes_tuple[0]
    end = indexes_tuple[1] + 1
    indexes = range(start, end)

    for i in indexes:
        if my_list[i]:
            return True
    return False

在 Python 中有更好的方法吗?

最佳答案

>>> my_list = [False, False, False, True, True, True]
>>> def contains_true(seq, bounds):
        start, end = bounds
        return any(seq[start:end+1])

>>> contains_true(my_list, (0,0))
False
>>> contains_true(my_list, (0,2))
False
>>> contains_true(my_list, (0,3))
True
>>> contains_true(my_list, (3,5))
True
>>> contains_true(my_list, (5,5))
True

关于Python - 评估列表子集的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11382224/

相关文章:

python - 如何使用 Python 保存数据库响应中字符串的完整性

java - 循环时为链表创建名称 (Java)

python - 如何避免 "WindowsError: [Error 5] Access is denied"

python - 使用 virtualenv 时 django settings.py 中 TEMPLATE_DIRS 的路径是什么

python - 处理 [Errno 111] 连接被 flask 中的请求拒绝返回

python utc 时间减去 5 分钟

python - 如何使用字典转换列表中的值

python - 将 unicode 字符串转换为其原始格式

python - 为给定特定列表的排序算法找到合理的计时测试

python-2.7 - 对 Tkinter bind_class 感到困惑