简体   繁体   English

如何确定一个列表是否包含另一个列表中的项目,然后在 Python 中打印它们的索引

[英]how do I determine if one list has items contained in another list, then print their index in Python

I want to determine if one list has items contained in another list.我想确定一个列表中是否包含另一个列表中的项目。 If that's the case, I want to print the index of such items:如果是这样,我想打印这些项目的索引:

List1 = [10, 20, 30]
List2 = [10, 50, 80, 90, 20, 30, 40, 50]

For example, I want to find 10 in List1 which is present in List2 , and print index 0 .例如,我想在List2存在的List1中找到10 ,并打印索引0 Is there any solution or direct function?有什么解决方案或直接功能吗?

#Finding intersection between two lists 
inter=set(List1)&set(List2)
for val in inter:
    #prints index of value which contains on both lists
    print List2.index(val)

Using a for loop and index method使用 for 循环和index方法

Demo:演示:

List1= [10,20,30] 
List2=[10,50,80,90,20,30,40,50]
for i in List1:
    if i in List2:
        print(List2.index(i))

Try this ;)尝试这个 ;)

List1,List2=[10,20,30],[10,50,80,90,20,30,40,50] #input
i = List1[0] #number you're looking for
for index in range(0,len(List2)):
    if List2[index] == i:
        print (index)   # if number is present

Try this:-尝试这个:-

ls = [i for i,x in enumerate(List2) if x in List1]
print(ls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM