记录平时学习中接触到的和网上看到的一些pythonic的方法,只为日后查询时候方便。
1.列表推导式:
seq_list=[1,2,3,4,5]
new_list=[i *2 for i in seq_list if i %2==0 ]
2.生成器表达式(减少内存占用)
seq_list=(i*2 for i in range(0,1000) )
3.强大的内置函数zip,可遍历两个可迭代对象。在将行转换为列时特别有用。(但似乎zip函数在处理大的数据时速度会比较慢)
list_1 = [1,2,3,4,5,6,7,8]
list_2 = [7,6,5,4,3,2,1]
for element in zip(list_1,list_2)
print(element)
###############
(1,7)
(2,6)
(3,5)
(4,4)
(5,3)
(6,2)
(7,1) #list_1中多出的元素会被自动忽略
4.*用于解构可迭代对象
当一个函数,如person,需要将列表person_list中所有的元素作为参数传入时只需要person(*person_list)即可。
5.参数*args用于定义函数接受的参数为任意数目,所有参数储存在名为args的列表中
def person(*args):
for name in args:
print("the person is %s"%name)
######################
person('A','B','C','D','E') #例一
names = ['A','B','C','D','E']
person(*names) #运用*解构names列表,如同例一
the person is A
the person is B
the person is C
the person is D
the person is E
6.上下文管理器
with open('file','r') as fh:
for line in fh.readlines():
print(line)
___________________________
使用with而不使用旧版本中的最后添加fh.close()的方法。使用with语句,在读完文件或则中途发生异常时,会自动关闭文件。而fh.close()方法在发生异常时不会正常关闭文件(因为代码在中途就停止了,无法执行到fh.close())
7.进度条控制
import sys
import time
for i in range(1,61):
sys.stdout.write('#'+'->'+'\b\b')
sys.stdout.flush()
time.sleep(0.5)
8.列表去重
a=[1,2,3,4,5,3,2,2,1]
b=list(set(a))
9.将嵌套列表转为单一列表
a=[[1,2],[3,4],[5,6]]
import itertools
b=list(itertools.chain.from_iterable(a))
10.列表复制
list_a = [1,2,3]
list_b = list_a#这种方法并没有实现复制,只不过list_a和list_b共同指向同一块内存,即储存[1,2,3]的地方。
正确的复制方式:
list_b =list_a[:]