Python 在列表及其子列表中查找成员
我想创建一个generate函数来查找列表中的子列表:Python 在列表及其子列表中查找成员,python,Python,我想创建一个generate函数来查找列表中的子列表: data=[‘费用’、[‘食物’、[‘膳食’、‘零食’、‘饮料’、‘交通’、[‘公共汽车’、‘铁路’]、‘收入’、[‘工资’、‘奖金’] #例如,如果我想在“食品”中查找,我希望输出为[食品、膳食、零食、饮料] 这就是我到目前为止所做的: def find_subcategories_gen(category, categories, found=False): if type(categories) == list:
data=[‘费用’、[‘食物’、[‘膳食’、‘零食’、‘饮料’、‘交通’、[‘公共汽车’、‘铁路’]、‘收入’、[‘工资’、‘奖金’]
#例如,如果我想在“食品”中查找,我希望输出为[食品、膳食、零食、饮料]
这就是我到目前为止所做的:
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
def find_subcategories_gen(category,categories,find=False):
如果类型(类别)=列表:
对于索引,枚举中的子项(类别):
查找子类别生成的产量(类别、子类别、错误)
如果child==类别和索引+1
这应该是有效的,但当我试图找到“食物”时,我得到的只是“食物”,而不是“食物”的父列表和子列表。
我应该如何处理这个问题?我添加了附加条件
并发现==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)))
['food', ['meal', 'snack', 'drink']]