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])
匿名函数
- lambda函数是一种快速定义单行的最小函数,可用在任何需要函数的地方。
- lambda函数优点:
- 省去定义函数过程,使代码更精简。
- 对于一些抽象的且不会被复用的函数而言,不用考虑给函数命名的问题。
- 在某些时候让代码更容易理解
- lambda语句中,冒号左边是参数,多个参数间用逗号隔开,冒号右边是返回值
- lambda语句构建的是一个函数对象
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