[英]Finding a member in a list and its sublist
I wanted to make a generate function to find a sublist inside a list:我想生成 function 以在列表中查找子列表:
data = ['expense', ['food', ['meal', 'snack', 'drink'], 'transportation', ['bus', 'railway']], 'income', ['salary', 'bonus']]
#for example if I want to find in 'food', I want the output to be [food, meal, snack , drink]
This is what I have so far:这是我到目前为止所拥有的:
def find_subcategories_gen(category, categories, found=False):
if type(categories) == list:
for index, child in enumerate(categories):
yield from find_subcategories_gen(category, child, False)
if child == category and index + 1 < len(categories) and type(categories[index + 1]) == list:
# When the target category is found,
# recursively call this generator on the subcategories
# with the flag set as True.
yield from find_subcategories_gen(category, categories[index+1], True)
else:
if categories == category or found == True:
yield categories
This should be working but when I try to find 'food', what I get is only 'food' instead of a list of the parent and the sublist of 'food'.这应该可以工作,但是当我尝试查找“食物”时,我得到的只是“食物”,而不是父列表和“食物”子列表。 How should I approach this?我应该如何处理这个?
I have added additional condition and found == False
我添加了附加条件and found == False
data = ['expense', ['food', ['meal', 'snack', 'drink'], 'transportation', ['bus', 'railway']], 'income', ['salary', 'bonus']]
def find_subcategories_gen(category, categories, found=False):
if type(categories) == list and found == False: #added found==False
for index, child in enumerate(categories):
yield from find_subcategories_gen(category, child, False)
if child == category and index + 1 < len(categories) and type(categories[index + 1]) == list:
# When the target category is found,
# recursively call this generator on the subcategories
# with the flag set as True.
yield from find_subcategories_gen(category, categories[index+1], True)
else:
if categories == category or found == True:
yield categories
print(list(find_subcategories_gen('food', data)))
Hence the output is因此 output 是
['food', ['meal', 'snack', 'drink']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.