Home > Back-end >  Get an element from a list next to a specific element when started from end of the list
Get an element from a list next to a specific element when started from end of the list

Time:10-15

I have a list items_list = [1,8,2,5,8,4,abc,gd,5,8]

I need to find 8 just after abc if started from end of the list. How can I do that ?

for example:- I have a list of files and everyday new file gets added to that list, I don't know the index of that file but I just know that I need to pick a file that comes just before a speicific file.

list is like this – [str_123.txt, zap_3456.log, str_678.txt, bcv_7886.log, abc.current, str_987.txt, zap_654.log]

I just need to pick str_678.txt, this file changes everyday and its position is also not constant but one thing is sure that this .txt file will come just before abc.current file. So what can I do in this case.

Expected output is :- str_678.txt

CodePudding user response:

Use the following:

files = ["str_123.txt", "zap_3456.log", "str_678.txt", "bcv_7886.log", "abc.current", "str_987.txt", "zap_654.log"]

# find the current index of abc.current
current_index = files.index("abc.current")

# get the next element that ends with .txt iterating backwards (-1) from current index
result = next(file for file in files[current_index::-1] if file.endswith(".txt"))

print(result)

Output

str_678.txt

CodePudding user response:

Iterate over the list using a while loop from the end.

When you find 'abc', you set a flag to True and start looking for the first number 8.

When you find the number 8 you return the index position and the actual number.

def find_first_8_after_abc(items):
    start = False
    index = len(items) - 1
    while index >= 0:
        if start and items[index] == 8:
            return (index, items[index])
        if items[index] == 'abc':
            start = True
        index -= 1


items_list = [1,8,2,5,8,4,'abc','gd',5,8]

location = find_first_8_after_abc(items_list)

print(location)

Will print (4, 8).

  • Related