Python two lists finding index value

后端 未结 2 1753
不知归路
不知归路 2021-01-14 06:55
listEx = [\'cat *(select: \"Brown\")*\', \'dog\', \'turtle\', \'apple\']
listEx2 = [\'hampter\',\' bird\', \'monkey\', \'banana\', \'cat\']

for j in listEx2:
    fo         


        
相关标签:
2条回答
  • 2021-01-14 07:01

    Just use 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"
    

    This will print

    cat found in cat *(select: "Brown")* at position 0 of listEx
    
    0 讨论(0)
  • 2021-01-14 07:22

    Your problem is that you wrote j instead of i in the last line:

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

    However, a better approach is to use enumerate:

    for item2 in listEx2:
        for i, item in enumerate(listEx):
            if item2 in item:
                print i
    
    0 讨论(0)
提交回复
热议问题