我有一個串列 items_list = [1,8,2,5,8,4,abc,gd,5,8]
如果從串列末尾開始,我需要在 abc 之后找到 8。我怎樣才能做到這一點 ?
例如:- 我有一個檔案串列,每天都有新檔案添加到該串列中,我不知道該檔案的索引,但我只知道我需要選擇一個位于特定檔案之前的檔案。
串列是這樣的——[str_123.txt, zap_3456.log, str_678.txt, bcv_7886.log, abc.current, str_987.txt, zap_654.log]
我只需要選擇 str_678.txt,這個檔案每天都在變化,它的位置也不是恒定的,但有一件事是確定這個 .txt 檔案會在 abc.current 檔案之前出現。那么在這種情況下我能做什么。
預期輸出是:- str_678.txt
uj5u.com熱心網友回復:
使用以下內容:
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)
輸出
str_678.txt
uj5u.com熱心網友回復:
最后使用 while 回圈遍歷串列。
找到后'abc',將標志設定為True并開始查找第一個數字8。
當您找到數字時,8您將回傳index位置和實際數字。
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)
會列印(4, 8)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314366.html
