简体   繁体   中英

Finding the index of the first element of a list in another list

main_list = ['4', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
my_list = ['4', '5', '6']

My question is, how to find index of my_list in main_list?

The integers in my_list must be in consecutive order in main_list.

I tried using main_list.index(my_list[0]) but if there are more than one of a specific element, it returns the wrong index number. The result I need to get is 4, however with main_list.index(my_list[0]) it'll just give 0 as its index.

If there is any need for clarification, I can edit the post with additional details. Sorry, English is not my first language.

Try something like this

for i in range(len(main_list)-len(my_list)):
    if main_list[i:i+len(my_list)] == my_list:
        index = i 
        break

This should work for all possible types that could go in the lists.

You can convert both lists into a string using join() function and iteratively compare the strings to find a match.

EDIT: Made a change for it two work for multi-digit numbers. Added a float case as well.

For example:

main_list = ['4', '1', '2', '3', '40.1', '52', '61', '7', '8', '9', '10']
my_list = ['40.1', '52', '61']
index = -1

for i in range(len(main_list)):
    if '#'.join(main_list[i:i+len(my_list)]) == '#'.join(my_list):
        index = i
        break

print(index)

If you would like an algorithm solution:

def Find(haystack, needle):
    n, h = len(needle), len(haystack)
    assert n <= h

    for i in range(h):
        if h - i <= n: break
        count = 0
        for i_, j in zip(range(i, i + n), range(n)):
            if haystack[i_] == needle[j]:
                count += 1
        if count == n: return i

    return -1

A much more effective one liner :

print ','.join(main_list).find(','.join(my_list)) - ''.join(main_list).find(''.join(my_list))

Converts them to strings with the elements separated by commas, finds the occurrence, then subtracts the occurrence found when the commas aren't there, and you have your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM