Discuss / Python / GvR大神说程序员大多数工作不需要递归

GvR大神说程序员大多数工作不需要递归

Topic source

1440K字节

#1 Created at ... [Delete] [Delete and Lock User]

于是写了个非递归版本的:

#!/usr/bin/env python3

import os
import sys

if len(sys.argv) != 2:
    sys.exit('Usage: %s PATTERN' % sys.argv[0])

str_pattern = sys.argv[1]
folders = ['.']
results = []

for folder in folders:
    folders += [os.path.join(folder, x) for x in os.listdir(folder) if os.path.isdir(os.path.join(folder, x))]
    results += [os.path.join(folder, y) for y in os.listdir(folder) if os.path.isfile(os.path.join(folder, y)) and str_pattern in y]

for result in results:
    print(result)

print('找到%s个满足条件的文件。' % len(results))

我是不是应该分一下行?

hwie

#2 Created at ... [Delete] [Delete and Lock User]

学习了@1440K字节

#递归
def myfilesearch0(dir,str):
    for d in os.listdir(dir):
        d0=os.path.join(dir,d)
        if os.path.isdir(d0):
            myfilesearch0(d0,str)
        elif os.path.isfile(d0) and str in os.path.split(d0)[1]:
            print(d0)

#不递归
def myfilesearch(dir,str):
    rs=[];
    flds=[dir]
    for d in flds:
        for x in os.listdir(d):
            k=os.path.join(d,x)
            if os.path.isdir(k):
                flds.append(k)
            elif os.path.isfile(k) and str in x:
                rs.append(k)

    print('%s files founded in searching \'%s\' at \'%s\':' % (len(rs),str,dir))
    for r in rs:
        print('%s'%r)
    return rs

myfilesearch0('.','jpeg')
myfilesearch('.','jpeg')

  • 1

Reply