[英]How to return objects from a list that matches certain criterias - Python
I'm Writing a search function where I'm searching through a list for matching Words or characters. 我正在编写一个搜索功能,在其中搜索要匹配的单词或字符的列表。 It looks like
看起来像
def search(seq, db):
return match(db, seq)
Where match is a recursive function which searches through the lists and returns a boolean value. 其中match是一个递归函数,它搜索列表并返回布尔值。 How do I return a list with the matching objects instead of just True or False?
如何返回带有匹配对象的列表,而不仅仅是True或False?
The match functions looks like this: 匹配函数如下所示:
def match(seq, pattern):
if not pattern:
return not seq
elif pattern[0] == '--':
if match(seq, pattern[1:]):
return True
elif not seq:
return False
else:
return match(seq[1:], pattern)
elif not seq:
return False
elif pattern[0] == '&':
return match(seq[1:], pattern[1:])
elif seq[0] == pattern[0]:
return match(seq[1:], pattern[1:])
elif isinstance(seq[0], list):
return match(seq[0], pattern)
elif isinstance(pattern[0], list):
return match(seq, pattern[0])
else:
return False
I don't really understand what your match
function is doing. 我不太了解您的
match
功能在做什么。 I'm guessing you're wanting the match
function to return a list instead of a boolean value. 我猜想您要让
match
函数返回一个列表,而不是布尔值。
You can start by changing your base cases. 您可以从更改基本案例开始。 Everywhere you see
return False
or return True
instead say 'return [] or
return [seq[0]] (assuming
seq[0]` is a sensible thing to be returned in your list of matches). 您看到的所有地方都
return False
或return True
而不是说'return [] or
return [seq [0]] (assuming
seq [0]`是在匹配列表中返回的明智之举)。
With your return match(...)
recursive cases you could return [seq[0]] + match(...)
or something similar to add the current match (when applicable) to the listed returned by the recursive call. 对于您的
return match(...)
递归案例,您可以return [seq[0]] + match(...)
或类似的东西,以将当前匹配项(如果适用)添加到递归调用返回的列表中。
This method of prepending lists is not particularly efficient, but I doubt that your concern now. 这种将列表放在前面的方法并不是特别有效,但是我怀疑您现在的担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.