Python两个查找索引值的列表
我试图完成的是在listEx中搜索Listx2中的项目。如果在listEx中找到Listx2中的项,我想知道如何打印在listEx中从Listx2中找到的项的索引值。谢谢 你的问题是你在最后一行写了Python两个查找索引值的列表,python,Python,我试图完成的是在listEx中搜索Listx2中的项目。如果在listEx中找到Listx2中的项,我想知道如何打印在listEx中从Listx2中找到的项的索引值。谢谢 你的问题是你在最后一行写了j而不是i: listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple'] listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat'] for j in listEx2: f
j
而不是i
:
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)
但是,更好的方法是使用枚举
:
for j in listEx2:
for i in listEx:
if j in i:
print listEx.index(i)
# ^ here
只需使用
枚举
:
for item2 in listEx2:
for i, item in enumerate(listEx):
if item2 in item:
print i
这会打印出来
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"
请不要只捕获任何异常,而只查找
ValueError
编辑:谢谢xDI想找到“cat(select:“Brown”)”的索引。你想找到“cat”
,因为它包含在“cat*(select:“Brown”)*”
中吗?如果listEx
中有多个项目包含字符串“cat”,该怎么办?你想要所有的索引吗?为什么我总是这么慢(-不管怎样,你的解决方案是好的,而且有效。
cat found in cat *(select: "Brown")* at position 0 of listEx