【发布时间】:2018-12-01 16:18:21
【问题描述】:
我正在尝试遍历嵌套列表并将其与模式匹配,然后创建匹配列表。但是,到目前为止,我的匹配功能只能通过最外层的列表。如何扩展它(匹配函数)以便它还可以读取数据库中的所有嵌套列表。代码如下:
database = [[['author', ['karl', 'jacksson']], ['title', ['jumping',
'high']], ['year', 2010]], [['author', ['keith', 'night']],
['title', ['chasing', 'shadows', 'in', 'the', 'dark']],
['year', 2012]]]
pattern = ['--', ['titel', ['&', '&']], '--']
('--'表示可以匹配0个或多个元素,'&'表示只能匹配一个元素)
def searching(pattern, database):
'''
Go through the database and see if anything matches the pattern
then create a list of all matched patterns
'''
return [i for i in database if matching(i, pattern)]
def matching(sequence, the_pattern):
"""
Returns if a given sequence matches the given pattern
"""
if not the_pattern:
return not sequence
elif the_pattern[0] == '--':
if matching(sequence, the_pattern[1:]):
return True
elif not sequence:
return False
else:
return matching(sequence[1:], the_pattern)
elif not sequence:
return False
elif the_pattern[0] == '&':
return matching(sequence[1:], the_pattern[1:])
elif sequence[0] == pattern[0]:
return matching(sequence[1:], the_pattern[1:])
else:
return False
这是一个例子:
输入
searching(['--', ['titel', ['&', '&']], '--'], database)
输出
[[['author', ['karl', 'jacksson']], ['title', ['jumping', 'high']],
['year', 2010]]]
【问题讨论】:
-
如果我正确地遵循了您的搜索逻辑,在您的示例中,您正在寻找任何标题长度为 2 的行?
-
是的,没错! @blacksite
-
好的。在您的情况下,似乎不需要递归。在下面查看我的答案,让我知道您的想法。
-
我想您可能对dpath 库感兴趣。这似乎可以做你想做的事。
标签: python list recursion nested-lists