一、递归
几种常用内置函数方法:
1)os.listdir():列出第一层目录文件
1
2
3
4
5
6
|
In [
14
]: os.listdir(
"/root/python"
)
Out[
14
]:
[
'20.py'
,
'1.py'
,
'19.py'
,
'21.py'
]
|
2)os.path.isdir():判断是不是目录
1
2
|
In [
13
]: os.path.isdir(
"/root/python"
)
Out[
13
]:
True
|
3)os.path.isfile():判断是不是文件
1
2
|
In [
15
]: os.path.isfile(
"/root/python/1.py"
)
Out[
15
]:
True
|
4)os.path.join():拼接路径
1
2
|
In [
16
]: os.path.join(
"/root/python"
,
"dir1"
,
"dir2"
)
Out[
16
]:
'/root/python/dir1/dir2'
|
练习:使用递归列出目录下的所有文件
1
2
3
4
5
6
7
8
9
10
11
|
#!/usr/bin/env python
import
os
import
sys
def
print_file(path):
lsdir
=
os.listdir(path)
for
i
in
lsdir:
if
os.path.isfile(os.path.join(path,i)):
print
os.path.join(path,i)
if
os.path.isdir(os.path.join(path,i)):
print_file(os.path.join(path,i))
print_file(sys.argv[
1
])
|
或:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/env python
import
os
import
sys
def
print_file(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
fl
in
files:
print
os.path.join(path,i)
if
dirs:
for
dr
in
dirs:
print_file(os.path.join(path,dr))
print_file(sys.argv[
1
])
|
二、匿名函数:lambda,冒号前是变量参数,冒号后是返回值
reduce()方法:无需定义函数,直接使用匿名函数即可
练习:累加
1
2
|
In [
18
]:
reduce
(
lambda
x,y:x
+
y,
range
(
1
,
101
))
Out[
18
]:
5050
|
三、内建函数
1)abs():绝对值
2)max() min():序列的最大最小值
3)len():取长度,序列和字典都可以
4)divmod():返回商和余数
5)pow(): 取幂
说明:两个数,幂;三个数,先幂,再取余数
6)round():保留小数位
说明:先变成浮点数,再保留小数
7)callable():判断一个对象是不是可调用的:函数、类可以调用,变量不可以调用
8)type():查看对象的类型
9)isinstance():判断是不是指定的类型
10)cmp():比较两个数字、字符串
11)range()、xrange():一个返回列表、一个返回对象(遍历时才有值)
12)complex():转变成一个负数
13)str():转换成字符串,可以是列表,也可以是字典
本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/2046840,如需转载请自行联系原作者