Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
停留在递归Python上_Python_Recursion - Fatal编程技术网

停留在递归Python上

停留在递归Python上,python,recursion,Python,Recursion,我的基本递归函数如下所示: 输入字符串的格式应为[[cow pig驴],'pig dog'] keep_track = [] def recursion(input_string, finding_name): list_names = list format [牛-猪-驴],[猪],[狗] for item in list_names: if item is A SINGLE WORLD: 猪 if name is finding_n

我的基本递归函数如下所示:

输入字符串的格式应为[[cow pig驴],'pig dog']

keep_track = []
def recursion(input_string, finding_name):
    list_names = list format
[牛-猪-驴],[猪],[狗]

    for item in list_names:
        if item is A SINGLE WORLD:

            if name is finding_name:
                keep_track append name
        else name is A LIST WITH MULTIPLE WORDS:
牛、猪、驴

            recursion([cow pig donkey], finding_name)
[牛],[猪],[驴]

这就是我被卡住的地方。因为我在结尾有一个返回语句

    return keep_track
如果我的递归被调用,我的函数将返回多次。我不确定如何修复我的函数,以便只返回一次

没有注释的功能

 keep_track = []
 def recursion(input_string, finding_name):
     list_names = basically would do this the first time
     for item in list_names:
         if item is A SINGLE WORLD:
             if name is finding_name:
                 keep_track append name
         else name is A LIST WITH MULTIPLE WORDS:
             recursion(item, finding_name)
     return list_names

你的问题一团糟,所以很难理解你想问什么。一个小时后,仍然不清楚。我要做一个最好的猜测来回答这个问题

看起来你已经得到了一个任意深度嵌套的字符串列表。比如:

in_lst = ['horse', 'cow', 'dog', ['pig', 'pig', 'horse'], 'cat', 'sheep']
您希望最终得到一个列表,其中包含某个特定字符串的所有匹配项

foo(in_lst, "pig") == ["pig", "pig"]
foo(in_lst, "horse") == ["horse", "horse"]
foo(in_lst, "dog") == ["dog"]
最简单的方法可能是展平列表,然后过滤(而不是直接递归)

如果出于某种原因必须直接递归(提示:不要),请尝试我在展平时使用的相同方法:

def find_names(haystack, needle):
    accum = []
    for el in lst:
        if hasattr(el, "__iter__") and not isinstance(el, str):
            accum.extend(find_names(el, needle))
        elif el == needle:
            accum.append(el)
    return accum
尽管可以说只是数数可能更容易

def find_names(haystack, needle):
    return [needle] * sum(1 for el in flatten(haystack) if el==needle)

请修复缩进。。。在Python中准确地理解是非常重要的,我不知道哪些行是哪些子句的一部分!您希望如何处理递归调用的结果?是否将其添加到列表中?递归调用将使[cow pig驴]变为[cow]、[pig]、[驴]。然后,我可以使用单个单词将其与我想要的内容进行比较,然后将其添加到列表中。我不能使用完整的句子,需要单独的单词。什么是
[牛猪驴]
?你的意思是
['cow'、'pig'、'驴子']
?很抱歉把代码弄混了,你确实明白我想做什么。我还必须使用递归为什么要测试
str
然后测试
basestring
?后者难道还不够吗?(Python 2版)@Two比特炼金术士我不知道。评论说用
basestring
test:)替换
str
test:)@AdamSmith-Oh我第一次误解了这一点。现在我明白了。
def find_names(haystack, needle):
    return [needle] * sum(1 for el in flatten(haystack) if el==needle)