【问题标题】:Iterating through database with nested lists使用嵌套列表遍历数据库
【发布时间】: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


【解决方案1】:

这里有一些建议/方法(正在进行中...将更新更多内容):

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

【讨论】:

  • 这适用于我给出的具体示例,但不适用于其他情况。例如,如果模式是:['--', ['year', 2095], '--'],那么它应该返回一个空列表(因为没有任何内容与 2095 年匹配)但是这个解决方案仍然会返回和之前的比赛一样。我认为搜索功能工作正常,但必须对匹配功能做一些事情才能使其能够通过多个列表。
  • 是的,您尝试解决许多不同的模式搜索案例。这是家庭作业吗?如果没有,一个实际的数据库将更完善的查询功能可能是值得的。
猜你喜欢
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 2015-12-06
  • 2021-09-19
  • 2021-10-30
相关资源
最近更新 更多