[英]Finding a sequence in list using another list In Python
我有一个list = [0, 0, 7]
和我的时候我比较反对它anotherList = [0, 0, 7, 0]
使用in
它给了我False
。
我想知道如何检查一个列表中的数字是否与另一个列表相同。
因此,如果我执行anotherList2 = [7, 0, 0, 0]
:
list in anotherList2
返回False
但是, list in anotherList
返回True
这是一个单线函数,它将检查列表a
是否在列表b
:
>>> def list_in(a, b):
... return any(map(lambda x: b[x:x + len(a)] == a, range(len(b) - len(a) + 1)))
...
>>> a = [0, 0, 7]
>>> b = [1, 0, 0, 7, 3]
>>> c = [7, 0, 0, 0]
>>> list_in(a, b)
True
>>> list_in(a, c)
False
>>>
您必须一一检查清单中的每个位置。 开始遍历anotherList
如果list的第一个元素与anotherList中的当前元素相同,则开始检查直到找到整个序列
该程序在这里:
def list_in(list,anotherList):
for i in range(0,len(anotherList)):
if(list[0]==anotherList[i]):
if(len(anotherList[i:]) >= len(list)):
c=0
for j in range(0,len(list)):
if(list[j]==anotherList[j+i]):
c += 1
if(c==len(list)):
print("True")
return
else:
continue
print("False")
return
list = [0,0,7]
anotherList = [0,0,7,0]
anotherList2 = [7,0,0,0]
list_in(list,anotherList)
list_in(list,anotherList2)
使用切片,编写高效的函数可以轻松实现所需的功能:
def sequence_in(seq, target):
for i in range(len(target) - len(seq) + 1):
if seq == target[i:i+len(seq)]:
return True
return False
我们可以这样使用:
sequence_in([0, 1, 2], [1, 2, 3, 0, 1, 2, 3, 4])
这里有一些很好的答案,但是这是您可以使用字符串作为媒介来解决它的另一种方法。
def in_ist(l1, l2):
return ''.join(str(x) for x in l1) in ''.join(str(y) for y in l2)
基本上,这会将列表中的元素转换为字符串,并使用in
运算符,它会检查l1
是否在l2
,从而达到您在这种情况下的预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.