Python两个列表查找索引值

3
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的项目的索引值。谢谢!


1
你想要找到 'cat' 吗?因为它包含在 'cat *(select: "Brown")*' 中吗? - Mark Byers
如果listEx中包含多个字符串“cat”,那么应该发生什么?您想要它们所有的索引吗? - Mark Byers
2个回答

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

为什么我总是这么慢?:( - 不管怎样,你的解决方案很好并且有效。 - Paul

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

请不要捕获任何异常,只寻找“ValueError”。- 编辑:谢谢 xD - poke
我想找到“猫(选择:“棕色”)”的索引。 - phales15

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接