簡體   English   中英

Python二列出查找索引值

[英]Python two lists finding index value

listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple']
listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']

for j in listEx2:
    for i in listEx:
        if j in i:
            print listEx.index(j)

我想要完成的是在listEx中搜索listEx2中的項目。 如果在listEx中找到listEx2中的項目,我想知道如何打印listEx中listEx2中找到的項目的索引值。 謝謝!

只需使用enumerate

listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple']
listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']

for j in listEx2:
    for pos, i in enumerate(listEx):
        if j in i:
            print j, "found in", i, "at position", pos, "of listEx"

這將打印

cat found in cat *(select: "Brown")* at position 0 of listEx

你的問題是你在最后一行寫了j而不是i

for j in listEx2:
    for i in listEx:
        if j in i:
            print listEx.index(i)
#                              ^ here

但是,更好的方法是使用enumerate

for item2 in listEx2:
    for i, item in enumerate(listEx):
        if item2 in item:
            print i

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM