简体   繁体   中英

Python: How to search a list from the middle outwards instead of searching from left to right like default?

My list looks like this list = ["a","b","c","b","a","c","b"] and I want to be able to search from the middle index outwards to find the first available "a". Using this logic it should search from index 3 then search indexes 2 and 4, then search indexes 1 and 5 then finally search indexes 0 and 6. If we apply this logic to our list, we search the list at index3 for "a" and it doesn't work, so we search indexes2 and 4 for "a" and we find it at index4

I tried using list.index("a") but that just returns the first available "a" at index0 when in reality I want the "a" at index4 since it is the closest to index3. I'm sorry if the answer is obvious, I am new to python and want to be able to search lists like this for a project of mine

I think I know a solution is to be able to start the search at index3 in the right direction and to also start a simultaneous search at index 3 in the left direction but I have no clue how to search in the left direction

EDIT: is there also a way to make it work if the middle is offset?

Try some good old math to get the middle element of the list.

mylist =  ["a","b","c","b","a","c","b"]
middle_index = (len(mylist) -1) / 2 # -1 since lists start at 0
middle_index = round(middle_index) # use round() if the list is even and middle_index variable is a float.

for index in range(middle_index): # loop over half the list
    value1 = mylist[middle_index-index] # get the variable left of the index
    value2 = mylist[middle_index+index] # get the variable right of the index
    if value1 == is "a":
        print("found!")
    if value2 == is "a":
        print("found!")
    

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