2018-11-29

2018-11-29  本文已影响0人  Karl_2c80

递归列出目录里的文件

#!/usr/bin/python
# -*- coding:utf-8 -*-

import os
import sys

def printFiles(path):
    lsdir = os.listdir(path)
    files = [i for i in lsdir if os.path.isfile(os.path.join(path, i))]
    dirs = [i for i in lsdir if os.path.isdir(os.path.join(path, i))]
    if files:
        for f in files:
            print os.path.join(path, f)
    if dirs:
        for d in dirs:
            printFiles(os.path.join(path, d))

printFiles(sys.argv[1])

匿名函数

  1. 省去定义函数过程,使代码更精简。
  2. 对于一些抽象的且不会被复用的函数而言,不用考虑给函数命名的问题。
  3. 在某些时候让代码更容易理解
In [11]: lambda x, y: x + y
Out[11]: <function __main__.<lambda>>
## <>表示对象
# 内置函数reduce()
reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
# lambda常见用法
In [1]: r = lambda x,y:x*y

In [2]: r(3, 4)
Out[2]: 12

In [3]: w = lambda x, y: x**y

In [4]: w(2, 3)
Out[4]: 8

In [5]: help(reduce)


In [6]: add = lambda x, y: x + y

In [7]: reduce(add, range(1, 101))
Out[7]: 5050

In [8]: reduce(lambda x, y: x + y, range(1, 101))
Out[8]: 5050

In [10]: reduce(lambda x, y: x * y, range(1, 6))
Out[10]: 120
上一篇下一篇

猜你喜欢

热点阅读