python列表可以不按顺序查找元素吗,查找元素是否在python列表中连续出现n次

myList = [True, True, False, False, True, False, True, False, False]

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

Is there a better way?

解决方案

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)

The if k filters the groups to only count the groups of True values.

The itertools.islice() function ensures we only look at the first 3 elements of a group, and ignore the rest of that group. This way you avoid having to count the next however many True values just to determine that you found at least 3.

Demo:

>>> 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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值