问题描述
myList = [True, True, False, False, True, False, True, False, False]
我想确定True是否连续出现3次.
I want to find if True appears 3 times in a row.
我可以通过以下方法找到它:
I can find it by doing:
for x0, x1, x2 in zip(myList, myList[1:], myList[2:]):
if x0 == True and x1 == True and x2 == True:
print True
有更好的方法吗?
推荐答案
使用 itertools.groupby()
对元素进行分组,然后对每个组进行计数.使用 any()
函数,如果匹配,您可以提早退出循环被发现:
Use itertools.groupby()
to group elements, then count each group. Using the any()
function lets you exit the loop early if a match was found:
from itertools import groupby, islice
print any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
if k
过滤组以仅计算True
值的组.
The if k
filters the groups to only count the groups of True
values.
itertools.islice()
函数确保我们仅查看组的前三个元素,而忽略该组的其余部分.这样,您就不必为了确定至少发现3个而计算下一个True
个下一个值.
演示:
>>> from itertools import groupby, islice
>>> myList = [True, True, False, False, True, False, True, False, False]
>>> [sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
[2, 1, 1]
>>> any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
False
>>> myList = [True, True, False, False, True, True, True, True, False, True, False, False]
>>> [sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
[2, 3, 1]
>>> any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
True
我使用列表推导来显示组的大小(仅计算True
个组),以显示为什么any()
调用首先返回False
,然后返回True
的原因;第二个示例包含一组4个连续的True
值.
I used a list comprehension to show the group sizes (counting only True
groups) to show why the any()
call returns False
first, then True
; the second example has a group of 4 consecutive True
values.
这篇关于查找元素是否在python列表中连续出现n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!