I have a list that I am using to process a series of tasks on directories. Occasionally the process will get stuck at a certain directory. Currently I'm removing that element and re-running the process thru the list. However, this is getting to take a while.
Here's what I'm doing now:
directories = next(os.walk('/home'))[1]
directories.remove('brokendirectory')
process_directory(directory)
What I'd like to do is to remove EVERY directory INCLUDING the directory that's broken and only work on the list of directories after that broken directory. Something like this:
def clear_list(directories, element):
new_list = []
for directory in directories:
if directory == element:
break
else:
new_list.append(directory)
return(new_list)
directories = next(os.walk('/home'))[1]
new_directories = clear_list(directories,'brokendirectory')
process_directory(new_directories)
Obviously my function does not work as-is.
How can I remove all elements in the list including the one specified and return a new list for processing?
您可以使用列表的 index 方法找到所需元素的索引,然后使用切片删除所有元素,包括它。
directories = directories[directories.index('brokendirectory')+1:]
Find the index of the broken directory:
idx = directories.index('brokendirectory')
Use that index to slice a new list:
new_directories = directories[idx+1:]
Then process that:
process_directory(new_directories)
You can use the function dropwhile
:
from itertools import dropwhile
l = 'ABCDEFG'
element = 'D'
list(dropwhile(lambda x: x != element, l))
# ['D', 'E', 'F', 'G']
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.