简体   繁体   English

如何使用python在另一个列表中找到一个列表?

[英]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 .如果您需要listblista索引位置。

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.

相关问题 如何以快速方式(python)查找一个列表中的日期时间是否落在另一个列表中的日期之间? - How do I find if a datetime in one list falls in between dates in another list in a quick manner (python)? 您如何在另一个列表中按顺序查找一个列表中的元素? - How do you find the elements in one list, in that order, in another list? 如何将一个列表的元素放在另一个列表的中间? 一维战舰游戏。 (蟒蛇) - How do I place the elements of a list into the middle of another list? A one dimensional battleship game. (Python) 如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度? - How do I add all integers in one list to integers on another list with different length in the same order in Python? 如何确定一个列表是否包含另一个列表中的项目,然后在 Python 中打印它们的索引 - how do I determine if one list has items contained in another list, then print their index in Python 如何在列表中找到重复项并使用它们创建另一个列表? - How do I find the duplicates in a list and create another list with them? 我应该如何在一个列表中找到并替换另一个列表(python)? - How should i find in a list and replace in another list(python)? 如何打印一个列表中另一个列表中的元素? - How do I print elements of one list that are in another list? 如何将一个列表中的元素添加到另一个列表中? - How do i add element from one list into another list? 如何检查一个列表是否包含另一个列表的 2 个元素? - How do I check if one list contains 2 elements of another list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM