Python在列表中的每个元素上调用递归函数

时间:2016-11-24 04:54:08

标签: python recursion

我正在处理这个名为traverseDir的递归函数,一切顺利,直到这里,我不知道如何迭代列表并在列表中的每个元素上调用我的traverseDir函数。如果你能提供帮助,非常感谢!

path = sys.argv[1]

def traverseDir(path):

    allFile = 0
    someFile = 0

    if os.path.isfile(path): # base case
        print(sys.argv[0])
        allFile += 1
        if path.endswith('.some'):
            someFile += 1

    else:
        files = os.listdir(path)
        return files

        #if len(files[0]) <= 1: these 2 lines are where I can't figure out
         #   return traverseDir(item)

2 个答案:

答案 0 :(得分:2)

一个名为os.walk的内置函数已经这样做了。但是,为了您的问题,您需要迭代files列表。您还需要将all_filessome_files传递给递归,以便它们可以随时累积。您还需要返回all_filessome_files(python允许您将多个值作为元组返回)。然后,您可以为all_filessome_files添加递归返回的值。

def traverseDir(path, all_files=0, some_files=0):
    # ... your existing code

    files = os.listdir(path)
    for f in files:
        # extend the path
        full_path = os.path.join(path, f)

        # unroll the returned values from the recursion
        rec_all_files, rec_some_files = traverseDir(full_path, all_files, some_files)
        # accumulate the values
        all_files += rec_all_files
        some_files += rec_some_files

    return all_files, some_files

这会在列出的每个文件上调用traverseDir()。反过来,该递归将在它列出的每个文件上调用traverseDir()

答案 1 :(得分:0)

<强> os.listdir

import sys
import os

path = sys.argv[1]


def traverseDir(path):
    allFile = 0
    someFile = 0
    if os.path.isfile(path):
        allFile += 1
        if path.endswith('.some'):
            someFile += 1
    else:
        for file in os.listdir(path):
            agAllFile, agSomeFile = traverseDir(os.path.join(path, file))
            allFile += agAllFile
            someFile += agSomeFile
    return allFile, someFile

print traverseDir(path)

<强> os.walk

import sys
import os

path = sys.argv[1]


def traverseDir(path):
    files = [file for dirFiles in os.walk(path) for file in dirFiles[2]]
    return len(files), len([file for file in files if file.endswith('.some')])

print traverseDir(path)