Я пытаюсь выполнить итерацию по вложенным спискам и сопоставить их с шаблоном, а затем создать список совпадений. Однако моя соответствующая функция может пройти только через внешний список. Как его можно развернуть (соответствующая функция), чтобы он также читал все вложенные списки в базе данных. Вот код:
database = [[['author', ['karl', 'jacksson']], ['title', ['jumping',
'high']], ['year', 2010]], [['author', ['keith', 'night']],
['title', ['chasing', 'shadows', 'in', 'the', 'dark']],
['year', 2012]]]
pattern = ['--', ['titel', ['&', '&']], '--']
('-' menas может соответствовать 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]]]
Вот несколько предложений/подходов (в процессе работы... будут обновлены дополнительные фрагменты):
database = [
[
['author', ['karl', 'jacksson']],
['title', ['jumping', 'high']],
['year', 2010]
],
[
['author', ['keith', 'night']],
['title', ['chasing', 'shadows', 'in', 'the', 'dark']],
['year', 2012]
]
]
# The pattern you specify, with a slight spelling correction:
pattern = ['--', ['title', ['&', '&']], '--']
# It seems you're jut interested in rows where 'title' is of length two
# so why not query the "database" like so?
def search(pattern, database):
for record in database:
# Assumes that your pattern is defined for all keys in each record
# i.e. if there are three "columns" in all records, then the pattern
# if of length three, as well
record_with_pattern = zip(record, pattern)
for (key, record_data), pattern_data in record_with_pattern:
# Might be simpler to just use 'None' instead of '--'
if pattern_data != '--':
if len(pattern_data) == len(record_data):
print('Match: {}'.format(str(record)))
search(pattern, database)
# Match: [['author', ['karl', 'jacksson']], ['title', ['jumping', 'high']], ['year', 2010]]