[英]How do i find one list in another list with python?
I have two lists:我有两个清单:
lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]
I want to find the first occurrence of the elements of listb in the order of listb in lista.我想在lista中按照listb的顺序找到listb的元素的第一次出现。
I have tried我试过了
print(lista.index(listb))
but it gives the error但它给出了错误
ValueError: [3, 4, 5] is not in list
I have also tried我也试过
np.where(np.array(lista)==np.array(listb))
but it returns但它返回
(array([], dtype=int64),)
What am I doing wrong?我究竟做错了什么?
The intended output with lista and listb should be 2. lista 和 listb 的预期输出应该是 2。
You can use a simple list comprehension
:您可以使用简单的
list comprehension
:
lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]
[print(f"Index = {x}") for x in range(len(lista)) if lista[x:x+3] == listb]
Output:输出:
Index = 2
If you need index position of your listb
in lista
.如果您需要
listb
在lista
索引位置。
Code代码
lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]
for i in listb:
if i in lista:
print (lista.index(i))
Output:输出:
2
3
4
print([lista.index(n) for n in listb])
flag2 = False
for i in lista:
if listb[0] == i:
c = lista.index(i)
k = c
flag = True
for j in range(len(listb)):
if listb[j] != lista[c]:
flag = False
break
c = c+1
if flag:
flag2 = True
print(k)
break
if not flag2:
print('Does not exist')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.