一、递归访问目录:且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
利用os.模块
import os
def list_dir_content(dir_path, count=0):
for file_name in os.listdir(dir_path):
sub_path = os.path.join(dir_path, file_name)
if os.path.isdir(sub_path):
print(count * "\t" + file_name)
sub_count = count + 1
list_dir_content(sub_path, sub_count)
if os.path.isfile(sub_path):
print(count * "\t" + file_name)
list_dir_content("D:\\test")
print(os.getcwd())
#运行结果
test.txt.txt
test1
test.xls.xls
test2
test.doc.doc
test3
test3.txt.txt
D:\Python\python_code
二、定义一个嵌套函数
功能:外层函数打印this is outing function,内层函数打印:This is inner function
def outing():
print('this is outing fuction')
def inner():
print('this is inner fuction')
inner()
outing()
#运行结果
this is outing fuction
this is inner fuction
三、定义一个递归函数:打印斐波那契序列
F[n]=F[n-1]+F[n-2] (n>=2,F[0]=0,F[1]=1)
def Fibonacci_series(n):
a = [0]
if n > 1:
a = [0, 1]
for i in range(n-2):
a.append(a[-2] + a[-1])
return a
print(Fibonacci_series(10))
#运行结果
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
四、对列表进行排序:list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
def get_three_char(str_data):
return str_data[-1], str_data[0]
list_data = ['grape','peach','berry','pineapple','apple','strayberry','watermelon']
list_data.sort(key=get_three_char)
print(list_data)
#运行结果
['apple', 'grape', 'pineapple', 'peach', 'watermelon', 'berry', 'strayberry']
五、利用map函数:计算三个列表相同位置元素之和
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
map(func, *iterables) --> map object
参数:
func: 函数
*iterable: 多个可迭代对象
返回值:返回map对象
功能:返回一个迭代器,执行函数,函数的参数是从每一个迭代对象中取一个元素,
当最短的可迭代对象被耗尽了就结束了
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
map_obj = map(lambda x, y, z: x+y+z, list1, list2, list3)
print(list(map_obj))
#运行结果
[12, 15, 18]
六、利用filter函数过滤列表中所有带a的字符串
list_data = [“grape”, “what”, “which”, “you”, “friend”, “am”]
filter(function or None, iterable) --> filter object
参数:
function or None: 函数或空
iterable: 一个可迭代对象
返回值: filter object: 一个filter类型的对象
功能: 过滤器
有function的情况,将iterable中的每一个元素传递function,
返回值为True保留,为False的过滤掉
没有function的情况, 将iterable中元素,类似于执行bool(item)
如果是True保留,False过滤
返回的是一个迭代器,产生的元素是来自iterable中元素作为参数传递给function
拿到值是True情况。 如果没有function的情况,返回元素本身为True的元素
利用lambda表达式
list_data = ['grape', 'what', 'which', 'you', 'friend', 'am']
fil_obj = filter(lambda x: 'a' not in x, list_data)
print(list(fil_obj))
#运行结果
['which', 'you', 'friend']
七、利用reduce计算1 + 2 + 3 … + 100之和
reduce: 之前也是放在builtins.py中的,只是后来做了迁移
reduce(function, sequence[, initial]) -> value
可以有两个参数,也可以有三个参数
function: 函数
sequence: 序列
initial: 初始化
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
((((1+2)+3)+4)+5)
第一次lambda中的x, y 列表中的1, 2
第二次lambda中的x, y 是 x=是第一次labmbda的结果, y=3
…
利用lambda表达式
from functools import reduce
red_v = reduce(lambda x, y: x+y, list(range(101)))
print(red_v)
#运行结果
5050
8万+

被折叠的 条评论
为什么被折叠?



