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.
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.
You can use a simple 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
.
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.