如何使用一行或两行检查Python列表是否只包含True和False?
我只希望允许列表中的第一个连续元素组是如何使用一行或两行检查Python列表是否只包含True和False?,python,python-3.x,Python,Python 3.x,我只希望允许列表中的第一个连续元素组是True,然后所有剩余元素都是False。我希望类似这些示例的列表返回True: [True] [False] [对,错] [真、假、假] [True,True,True,False] 和类似的列表返回False: [假,真] [真、假、真] 我目前正在使用此功能,但我觉得可能有更好的方法: def my_function(x): n_trues = sum(x) should_be_true = x[:n_trues] # get
True
,然后所有剩余元素都是False
。我希望类似这些示例的列表返回True
:
[True]
[False]
[对,错]
[真、假、假]
[True,True,True,False]
False
:
[假,真]
[真、假、真]
def my_function(x):
n_trues = sum(x)
should_be_true = x[:n_trues] # get the first n items
should_be_false = x[n_trues:len(x)] # get the remaining items
# return True only if all of the first n elements are True and the remaining
# elements are all False
return all(should_be_true) and all([not element for element in should_be_false])
测试:
test_cases = [[True], [False],
[True, False],
[True, False, False],
[True, True, True, False],
[False, True],
[True, False, True]]
print([my_function(test_case) for test_case in test_cases])
# expected output: [True, True, True, True, True, False, False]
是否可以使用理解来代替,使其成为一行/两行函数?我知道我无法定义这两个临时列表,而是将它们的定义替换为返回行中的名称,但我认为这太混乱了。方法1 你可以用。这将避免对列表进行多次传递,也将避免首先创建临时列表:
def check(x):
status = list(k for k, g in groupby(x))
return len(status) <= 2 and (status[0] is True or status[-1] is False)
就我个人而言,我认为方法1完全是矫枉过正。方法2更好、更简单,并且更快地实现相同的目标。如果测试失败,它也会立即停止,而不必处理整个组。它也根本不分配任何临时列表,即使对于组聚合也是如此。最后,它处理开箱即用的空输入和非布尔输入
由于我是在手机上写作,这里有一个IDEOne链接供验证:没有任何是最简单的否定。我投票将这个问题作为离题题题来结束,因为它属于感谢,这是从一个问题开始的,但在我写作时,它更像是一个代码审查。我将在那里发布。我已经用我认为客观上最简单的解决方案更新了我的答案。
def check(x):
status = list(k for k, g in groupby(map(book, x)))
return status and len(status) <= 2 and (status[0] or not status[-1])
return not status or (len(status) <= 2 and (status[0] or not status[-1]))
def check(x):
iterator = iter(x)
# process the true elements
all(iterator)
# check that there are no true elements left
return not any(iterator)