1.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
4.对列表进行排序: list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
5.利用map函数: 计算三个列表,相同位置元素之和list1 = [1, 2, 3]list2 = [4, 5, 6]list3 = [7, 8, 9]
6.利用filter函数过滤列表中所有带a的字符串list_data = ["grape", "what", "which", "you", "friend", "am"]
1.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
先在D盘新建一个目录data,data目录中包含一个data1文件夹和data.txt文件,data1文件夹中包含data2和data.xsl,data2文件夹中包含data3和data.doc,data2文件夹中包含data3.txt
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())
data.txt.txt
data1
data.xls.xls
data2
data.doc.doc
data3
datat3.txt.txt
D:\Python\python_code
2.定义一个嵌套函数,
外层函数打印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
3.定义一个递归函数:打印斐波那契数列
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]
4.对列表进行排序: 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']
5.利用map函数: 计算三个列表,相同位置元素之和
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
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]
6.利用filter函数过滤列表中所有带a的字符串
list_data = ["grape", "what", "which", "you", "friend", "am"]
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']
7.利用reduce计
from functools import reduce
red_v = reduce(lambda x, y: x+y, list(range(101)))
print(red_v)
5050
算1 + 2 + 3...+ 100之和
173

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



