使用嵌套列表遍历数据库

时间:2018-12-01 16:18:22

标签: python list recursion nested-lists

我正在尝试遍历嵌套列表并将其与模式匹配,然后创建匹配列表。但是到目前为止,我的匹配功能只能通过最外面的列表。如何扩展它(匹配函数),使其还可以读取数据库中的所有嵌套列表。这是代码:

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]]]    

1 个答案:

答案 0 :(得分:0)

以下是一些建议/方法(进行中...将更新其他内容)

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]]