Python高级进阶详细笔记

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/zhang__shuang_/article/details/82555898

上几篇文章分别对Python的基础语法及小型项目进行介绍,接下来对Python的高级用法进行总结。这篇文章将会包括:迭代,列表,map()/reduce(),sorted(),生成器,过滤器,正则表达式等相关内容。

#Python高级特性--迭代
#如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple这种遍历我们称为迭代。
#在Python中,迭代是通过for ... in来完成的
#字典的迭代
d={'2':2,'3':3}
for key,value in d.items():#for key in d or for value in d.values()
    print(key)


for x, y in [(1, 1), (2, 4), (3, 9)]:
     print(x, y)


#如果要对list实现类似Java那样的下标循环怎么办?
#Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
for i, value in enumerate(['A', 'B', 'C']):
     print(i, value)
    



#Python高级特性--列表生成式
l=[x * x for x in range(1, 11)
l=[x * x for x in range(1, 11) if x % 2 == 0]
#还可以使用两层循环,可以生成全排列:
l=[m + n for m in 'ABC' for n in 'XYZ']


#列出当前目录下的所有文件和目录名,可以通过一行代码实现:
import os # 导入os模块,模块的概念后面讲到
[d for d in os.listdir('.')] # os.listdir可以列出文件和目录


#Python高级特性--生成器
#列表受内存限制容量是有限的,从而产生边循环边计算的机制:生成器(generator)


#Python高阶函数map及reduce
def f(x):
     return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list(r)

#reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
from functools import reduce
def fn(x, y):
     return x * 10 + y
reduce(fn, [1, 3, 5, 7, 9])
#13579


#Python高阶函数filter()函数用于过滤序列。
def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]


#Python高阶函数sorted()
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)


#偏函数:functools.partial。作用就是把一个函数的某些参数给固定住(也就是设置默认值)
#返回一个新的函数,调用这个新函数会更简单。
import functools
int2 = functools.partial(int, base=2)
int2('1000000')
#64
int2('1010101')
#85


#Pyhon正则表达式(re模块)
re.split(r'\s+', 'a b   c')
#['a', 'b', 'c']

#分组
 m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
#m:<_sre.SRE_Match object; span=(0, 9), match='010-12345'>
m.group(0)
#'010-12345'
m.group(1)
#'010'
m.group(2)
#'12345'

#贪婪匹配
re.match(r'^(\d+)(0*)$', '102300').groups()
#('102300', '')

#非贪婪匹配
re.match(r'^(\d+?)(0*)$', '102300').groups()
#('1023', '00')

猜你喜欢

转载自blog.csdn.net/zhang__shuang_/article/details/82555898
今日推荐