Python中两个列表寻找索引值
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中的位置索引。谢谢!
2 个回答
3
你的问题是你在最后一行写了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
4
只需要使用 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