[英]Python - How to check if next few elements in list meet some statement
I have a huge list of values, and I want to search for pattern: if listItem == some value and next 10 items in list meet some statement, then do something.我有一个巨大的值列表,我想搜索模式:如果 listItem == some value 并且列表中的下 10 个项目满足某个语句,那么做一些事情。 How to do this to avoid long multiple if condition code like that?如果条件代码那样,如何避免长倍数?
for i in range (0, len(list)):
if list[i] == someValue and list[i+1] !=someValue and list[i+2] !=someValue and [...] and list[i+10] !=someValue:
doSomething()
You can do it like this:你可以这样做:
for i in range(len(lst)):
if lst[i] == someValue and all(x != someValue for x in lst[i+1:i+11]):
doSomething()
I changed the variable name from list
to lst
because you shopuld not overwrite the list
builtin type and I also removed the 0
in the range
fucntion as it is not needed.我将变量名称从list
更改为lst
因为您不会覆盖list
内置类型,并且我还删除了range
功能中的0
,因为它不需要。
The all
fucntion checks that every element in the iterable passed as argument evaluates to True
, and our iterable is a sequence of bools with the next 10 elements checked against someValue
. all
函数检查作为参数传递的迭代中的每个元素的计算结果为True
,我们的迭代是一个布尔序列,接下来的 10 个元素根据someValue
进行检查。
Another option would be using enumerate(...)
to avoid having to get the value again from the list instead of range(len(...))
:另一种选择是使用enumerate(...)
以避免再次从列表中获取值而不是range(len(...))
:
for i, value in enumerate(lst):
if value == someValue and all(x != someValue for x in lst[i+1:i+11]):
doSomething()
And we could make it into a generator:我们可以把它变成一个生成器:
for i in (i for i, value in enumerate(lst) if value == someValue and all(x != someValue for x in lst[i+1:i+11])):
doSomething()
@HeapOverflow suggested another way to check for that condition which is more readable (see his answer for further detail and drop a like) that conbined with the generator syntax would be: @HeapOverflow 建议了另一种检查该条件的方法,该方法与生成器语法相结合,该方法更具可读性(请参阅他的回答以获取更多详细信息并删除类似内容):
for i in (i for i, value in enumerate(lst) if value == someValue not in lst[i+1:i+11]):
doSomething()
Did you mean that you are searching for arbitrary values?您的意思是您正在搜索任意值吗?
target = [someValue1, someValue2, ... someValue11]
for i in range (len(lst) - 10):
if lst[i:i+11] == target:
doSomething()
Try this:尝试这个:
for i in range (0, len(list)):
if list[i] == someValue and all(x != someValue for x in list[i+1:i+10]):
doSomething()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.