您现在的位置是:首页 > 技术教程 正文

python编程常用代码,python常用代码大全

admin 阅读: 2024-03-24
后台-插件-广告管理-内容页头部广告(手机)

ef55fe5af611a8a6a5253ef27869d2ad.gif

作者 | 快学Python

来源 | https://github.com/jackzhenguo/python-small-examples

今天给大家分享一下60个Python小例子,拿来即用!

一、 数字

1、求绝对值

绝对值或复数的模

  1. # 公众号:快学Python
  2. In [1]: abs(-6)  
  3. Out[1]: 6
2 进制转化

十进制转换为二进制:

  1. In [2]: bin(10)  
  2. Out[2]: '0b1010'

十进制转换为八进制:

  1. In [3]: oct(9)  
  2. Out[3]: '0o11'

十进制转换为十六进制:

  1. In [4]: hex(15)  
  2. Out[4]: '0xf'
3 整数和ASCII互转

十进制整数对应的ASCII字符

  1. In [1]: chr(65)  
  2. Out[1]: 'A'

查看某个ASCII字符对应的十进制数

  1. In [1]: ord('A')  
  2. Out[1]: 65
4 元素都为真检查

所有元素都为真,返回 True,否则为False

  1. In [5]: all([1,0,3,6])  
  2. Out[5]: False
  1. In [6]: all([1,2,3])  
  2. Out[6]: True
5 元素至少一个为真检查

至少有一个元素为真返回True,否则False

  1. In [7]: any([0,0,0,[]])  
  2. Out[7]: False
  1. In [8]: any([0,0,1])  
  2. Out[8]: True
6 判断是真是假

测试一个对象是True, 还是False.

  1. In [9]: bool([0,0,0])  
  2. Out[9]: True  
  3.   
  4. In [10]: bool([])  
  5. Out[10]: False  
  6.   
  7. In [11]: bool([1,0,1])  
  8. Out[11]: True
7 创建复数

创建一个复数

  1. In [1]: complex(1,2)  
  2. Out[1]: (1+2j)
8 取商和余数

分别取商和余数

  1. In [1]: divmod(10,3)  
  2. Out[1]: (31)
9 转为浮点类型

将一个整数或数值型字符串转换为浮点数

  1. In [1]: float(3)  
  2. Out[1]: 3.0

如果不能转化为浮点数,则会报ValueError:

  1. In [2]: float('a')  
  2. # ValueError: could not convert string to float: 'a'
10 转为整型

int(x, base =10) , x可能为字符串或数值,将x 转换为一个普通整数。如果参数是字符串,那么它可能包含符号和小数点python自动化运维。如果超出了普通整数的表示范围,一个长整数被返回。

  1. In [1]: int('12',16)  
  2. Out[1]: 18
11 次幂

base为底的exp次幂,如果mod给出,取余

  1. In [1]: pow(324)  
  2. Out[1]: 1
12 四舍五入

四舍五入,ndigits代表小数点后保留几位:

  1. In [11]: round(10.02222223)  
  2. Out[11]: 10.022  
  3.   
  4. In [12]: round(10.05,1)  
  5. Out[12]: 10.1
13 链式比较
  1. i = 3  
  2. print(1 < i < 3)  # False  
  3. print(1 < i <= 3)  # True

二、 字符串

14 字符串转字节

字符串转换为字节类型

  1. In [12]: s = "apple"                                                              
  2.   
  3. In [13]: bytes(s,encoding='utf-8')  
  4. Out[13]: b'apple'
15 任意对象转为字符串
  1. In [14]: i = 100                                                                  
  2.   
  3. In [15]: str(i)  
  4. Out[15]: '100'  
  5.   
  6. In [16]: str([])  
  7. Out[16]: '[]'  
  8.   
  9. In [17]: str(tuple())  
  10. Out[17]: '()'
16 执行字符串表示的代码

将字符串编译成python能识别或可执行的代码,也可以将文字读成字符串再编译。

  1. In [1]: s  = "print('helloworld')"  
  2.       
  3. In [2]: r = compile(s,"""exec")  
  4.       
  5. In [3]: r  
  6. Out[3]:  at 0x0000000005DE75D0, file "", line 1>  
  7.       
  8. In [4]: exec(r)  
  9. helloworld
17 计算表达式

将字符串str 当成有效的表达式来求值并返回计算结果取出字符串中内容

  1. In [1]: s = "1 + 3 +5"  
  2.     ...: eval(s)  
  3.     ...:  
  4. Out[1]: 9
18 字符串格式化

格式化输出字符串,format(value, format_spec)实质上是调用了value的__format__(format_spec)方法。

  1. In [1]: print("i am {0},age{1}".format("tom",18))  
  2. Out[1]:i am tom,age18

a0d92800b1c3839b23cb18155761568c.png

三、 函数

19 拿来就用的排序函数

排序:

  1. In [1]: a = [1,4,2,3,1]  
  2.   
  3. In [2]: sorted(a,reverse=True)  
  4. Out[2]: [43211]  
  5.   
  6. In [3]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'  
  7.      ...: xiaohong','age':20,'gender':'female'}]  
  8. In [4]: sorted(a,key=lambda x: x['age'],reverse=False)  
  9. Out[4]:  
  10. [{'name''xiaoming''age'18'gender''male'},  
  11.  {'name''xiaohong''age'20'gender''female'}]
20 求和函数

求和:

  1. In [181]: a = [1,4,2,3,1]  
  2.   
  3. In [182]: sum(a)  
  4. Out[182]: 11  
  5. # 公众号:快学Python
  6. In [185]: sum(a,10) #求和的初始值为10  
  7. Out[185]: 21
21 nonlocal用于内嵌函数中

关键词nonlocal常用于函数嵌套中,声明变量i为非局部变量;如果不声明,i+=1表明i为函数wrapper内的局部变量,因为在i+=1引用(reference)时,i未被声明,所以会报unreferenced variable的错误。

  1. def excepter(f):  
  2.     i = 0  
  3.     t1 = time.time()  
  4.     def wrapper():  
  5.         try:  
  6.             f()  
  7.         except Exception as e:  
  8.             nonlocal i  
  9.             i += 1  
  10.             print(f'{e.args[0]}: {i}')  
  11.             t2 = time.time()  
  12.             if i == n:  
  13.                 print(f'spending time:{round(t2-t1,2)}')  
  14.     return wrapper
22 global 声明全局变量

先回答为什么要有global,一个变量被多个函数引用,想让全局变量被所有函数共享。有的伙伴可能会想这还不简单,这样写:

  1. i = 5  
  2. def f():  
  3.     print(i)  
  4.   
  5. def g():  
  6.     print(i)  
  7.     pass  
  8.   
  9. f()  
  10. g()

f和g两个函数都能共享变量i,程序没有报错,所以他们依然不明白为什么要用global.

但是,如果我想要有个函数对i递增,这样:

  1. def h():  
  2.     i += 1  
  3.   
  4. h()

此时执行程序,bang, 出错了!抛出异常:UnboundLocalError,原来编译器在解释i+=1时会把i解析为函数h()内的局部变量,很显然在此函数内,编译器找不到对变量i的定义,所以会报错。

global就是为解决此问题而被提出,在函数h内,显式地告诉编译器i为全局变量,然后编译器会在函数外面寻找i的定义,执行完i+=1后,i还为全局变量,值加1:

  1. i = 0  
  2. def h():  
  3.     global i  
  4.     i += 1  
  5.   
  6. h()  
  7. print(i)
23 交换两元素
  1. def swap(a, b):  
  2.     return b, a  
  3. print(swap(10))

输出:

019dc3d0921723c55fd50d9b22d3a500.png
24 操作函数对象
  1. In [31]: def f():  
  2.     ...:     print('i'm f')  
  3.     ...:  
  4.   
  5. In [32]: def g():  
  6.     ...:     print('i'm g')  
  7.     ...:  
  8.   
  9. In [33]: [f,g][1]()  
  10. i'm g

创建函数对象的list,根据想要调用的index,方便统一调用。

25 生成逆序序列
list(range(10,-1,-1)) # [109876543210]

第三个参数为负时,表示从第一个参数开始递减,终止到第二个参数(不包括此边界)

26 函数的五类参数使用例子

python五类参数:位置参数,关键字参数,默认参数,可变位置或关键字参数的使用。

  1. def f(a,*b,c=10,**d):  
  2.   print(f'a:{a},b:{b},c:{c},d:{d}')

默认参数c不能位于可变关键字参数d后.

调用f:

  1. In [10]: f(1,2,5,width=10,height=20)  
  2. a:1,b:(25),c:10,d:{'width'10'height'20}

可变位置参数b实参后被解析为元组(2,5);而c取得默认值10; d被解析为字典.

再次调用f:

  1. In [11]: f(a=1,c=12)  
  2. a:1,b:(),c:12,d:{}

a=1传入时a就是关键字参数,b,d都未传值,c被传入12,而非默认值。

注意观察参数a, 既可以f(1),也可以f(a=1) 其可读性比第一种更好,建议使用f(a=1)。如果要强制使用f(a=1),需要在前面添加一个星号:

  1. def f(*,a,**b): 
  2.     print(f'a:{a},b:{b}')

此时f(1)调用,将会报错:TypeError: f() takes 0 positional arguments but 1 was given

只能f(a=1)才能OK.

说明前面的*发挥作用,它变为只能传入关键字参数,那么如何查看这个参数的类型呢?借助python的inspect模块:

  1. In [22]: for name,val in signature(f).parameters.items():  
  2.     ...:     print(name,val.kind)  
  3.     ...:  
  4. a KEYWORD_ONLY  
  5. b VAR_KEYWORD

可看到参数a的类型为KEYWORD_ONLY,也就是仅仅为关键字参数。

但是,如果f定义为:

  1. def f(a,*b):  
  2.     print(f'a:{a},b:{b}')

查看参数类型:

  1. In [24]: for name,val in signature(f).parameters.items():  
  2.     ...:     print(name,val.kind)  
  3.     ...:  
  4. a POSITIONAL_OR_KEYWORD  
  5. b VAR_POSITIONAL

可以看到参数a既可以是位置参数也可是关键字参数。

27 使用slice对象

生成关于蛋糕的序列cake1:

  1. In [1]: cake1 = list(range(5,0,-1))  
  2.   
  3. In [2]: b = cake1[1:10:2]  
  4.   
  5. In [3]: b  
  6. Out[3]: [42]  
  7.   
  8. In [4]: cake1  
  9. Out[4]: [54321]

再生成一个序列:

  1. In [5]: from random import randint  
  2.    ...: cake2 = [randint(1,100for _ in range(100)]  
  3.    ...: # 同样以间隔为2切前10个元素,得到切片d  
  4.    ...: d = cake2[1:10:2]  
  5. In [6]: d  
  6. Out[6]: [7533639315]

你看,我们使用同一种切法,分别切开两个蛋糕cake1,cake2. 后来发现这种切法极为经典,又拿它去切更多的容器对象。

那么,为什么不把这种切法封装为一个对象呢?于是就有了slice对象。

定义slice对象极为简单,如把上面的切法定义成slice对象:

  1. perfect_cake_slice_way = slice(1,10,2)  
  2. #去切cake1  
  3. cake1_slice = cake1[perfect_cake_slice_way]  
  4. cake2_slice = cake2[perfect_cake_slice_way]  
  5.   
  6. In [11]: cake1_slice  
  7. Out[11]: [42]  
  8.   
  9. In [12]: cake2_slice  
  10. Out[12]: [7533639315]

与上面的结果一致。

对于逆向序列切片,slice对象一样可行:

  1. a = [1,3,5,7,9,0,3,5,7]  
  2. a_ = a[5:1:-1]  
  3.   
  4. named_slice = slice(5,1,-1)  
  5. a_slice = a[named_slice]  
  6.   
  7. In [14]: a_  
  8. Out[14]: [0975]  
  9.   
  10. In [15]: a_slice  
  11. Out[15]: [0975]

频繁使用同一切片的操作可使用slice对象抽出来,复用的同时还能提高代码可读性。

28 lambda 函数的动画演示

有些读者反映,lambda函数不太会用,问我能不能解释一下。

比如,下面求这个 lambda函数:

  1. def max_len(*lists):  
  2.     return max(*lists, key=lambda v: len(v))

有两点疑惑:

  • 参数v的取值?

  • lambda函数有返回值吗?如果有,返回值是多少?

调用上面函数,求出以下三个最长的列表:

  1. r = max_len([123], [4567], [8])  
  2. print(f'更长的列表是{r}')

程序完整运行过程,动画演示如下:

473edf9cafca53407831d93b62b88d37.gif

结论:

  • 参数v的可能取值为*lists,也就是 tuple 的一个元素。

  • lambda函数返回值,等于lambda v冒号后表达式的返回值。

四、 数据结构

29 转为字典

创建数据字典

  1. In [1]: dict()  
  2. Out[1]: {}  
  3.   
  4. In [2]: dict(a='a',b='b')  
  5. Out[2]: {'a''a''b''b'}  
  6.   
  7. In [3]: dict(zip(['a','b'],[1,2]))  
  8. Out[3]: {'a'1'b'2}  
  9.   
  10. In [4]: dict([('a',1),('b',2)])  
  11. Out[4]: {'a'1'b'2}
30 冻结集合

创建一个不可修改的集合。

  1. In [1]: frozenset([1,1,3,2,3])  
  2. Out[1]: frozenset({123})

因为不可修改,所以没有像set那样的add和pop方法

31 转为集合类型

返回一个set对象,集合内不允许有重复元素:

  1. In [159]: a = [1,4,2,3,1]  
  2.   
  3. In [160]: set(a)  
  4. Out[160]: {1234}
32 转为切片对象

class slice(startstop[, step])

返回一个表示由 range(start, stop, step) 所指定索引集的 slice对象,它让代码可读性、可维护性变好。

  1. In [1]: a = [1,4,2,3,1]  
  2.   
  3. In [2]: my_slice_meaning = slice(0,5,2)  
  4.   
  5. In [3]: a[my_slice_meaning]  
  6. Out[3]: [121]
33 转元组

tuple() 将对象转为一个不可变的序列类型

  1. In [16]: i_am_list = [1,3,5]  
  2. In [17]: i_am_tuple = tuple(i_am_list)  
  3. In [18]: i_am_tuple  
  4. Out[18]: (135)

五、 类和对象

34 是否可调用

检查对象是否可被调用

  1. In [1]: callable(str)  
  2. Out[1]: True  
  3.   
  4. In [2]: callable(int)  
  5. Out[2]: True
  1. In [18]: class Student():  
  2.     ...:     def __init__(self,id,name):  
  3.     ...:         self.id = id   
  4.     ...:         self.name = name   
  5.     ...:     def __repr__(self):  
  6.     ...:         return 'id = '+self.id +', name = '+self.name   
  7.     ...  
  8.   
  9. In [19]: xiaoming = Student('001','xiaoming')  
  10.   
  11. In [20]: callable(xiaoming)  
  12. Out[20]: False

如果能调用xiaoming(), 需要重写Student类的__call__方法:

  1. In [1]: class Student():  
  2.     ...:     def __init__(self,id,name):  
  3.     ...:         self.id = id  
  4.     ...:         self.name = name  
  5.     ...:     def __repr__(self):  
  6.     ...:         return 'id = '+self.id +', name = '+self.name  
  7.     ...:     def __call__(self):  
  8.     ...:         print('I can be called')  
  9.     ...:         print(f'my name is {self.name}')  
  10.     ...:  
  11.   
  12. In [2]: t = Student('001','xiaoming')  
  13.   
  14. In [3]: t()  
  15. I can be called  
  16. my name is xiaoming
35 ascii 展示对象

调用对象的 __repr__ 方法,获得该方法的返回值,如下例子返回值为字符串

  1. >>> class Student():  
  2.     def __init__(self,id,name):  
  3.         self.id = id  
  4.         self.name = name  
  5.     def __repr__(self):  
  6.         return 'id = '+self.id +', name = '+self.name

调用:

  1. >>> xiaoming = Student(id='1',name='xiaoming')  
  2. >>> xiaoming  
  3. id = 1, name = xiaoming  
  4. >>> ascii(xiaoming)  
  5. 'id = 1, name = xiaoming'
36 类方法

classmethod 装饰器对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

  1. In [1]: class Student():  
  2.     ...:     def __init__(self,id,name):  
  3.     ...:         self.id = id  
  4.     ...:         self.name = name  
  5.     ...:     def __repr__(self):  
  6.     ...:         return 'id = '+self.id +', name = '+self.name  
  7.     ...:     @classmethod  
  8.     ...:     def f(cls):  
  9.     ...:         print(cls)
37 动态删除属性

删除对象的属性

  1. In [1]: delattr(xiaoming,'id')  
  2.   
  3. In [2]: hasattr(xiaoming,'id')  
  4. Out[2]: False
38 一键查看对象所有方法

不带参数时返回当前范围内的变量、方法和定义的类型列表;带参数时返回参数的属性,方法列表。

  1. In [96]: dir(xiaoming)  
  2. Out[96]:  
  3. ['__class__',  
  4.  '__delattr__',  
  5.  '__dict__',  
  6.  '__dir__',  
  7.  '__doc__',  
  8.  '__eq__',  
  9.  '__format__',  
  10.  '__ge__',  
  11.  '__getattribute__',  
  12.  '__gt__',  
  13.  '__hash__',  
  14.  '__init__',  
  15.  '__init_subclass__',  
  16.  '__le__',  
  17.  '__lt__',  
  18.  '__module__',  
  19.  '__ne__',  
  20.  '__new__',  
  21.  '__reduce__',  
  22.  '__reduce_ex__',  
  23.  '__repr__',  
  24.  '__setattr__',  
  25.  '__sizeof__',  
  26.  '__str__',  
  27.  '__subclasshook__',  
  28.  '__weakref__',  
  29.    
  30.  'name']
39 动态获取对象属性

获取对象的属性

  1. In [1]: class Student():  
  2.    ...:     def __init__(self,id,name):  
  3.    ...:         self.id = id  
  4.    ...:         self.name = name  
  5.    ...:     def __repr__(self):  
  6.    ...:         return 'id = '+self.id +', name = '+self.name  
  7.   
  8. In [2]: xiaoming = Student(id='001',name='xiaoming')  
  9. In [3]: getattr(xiaoming,'name') # 获取xiaoming这个实例的name属性值  
  10. Out[3]: 'xiaoming'
40 对象是否有这个属性
  1. In [1]: class Student():  
  2.    ...:     def __init__(self,id,name):  
  3.    ...:         self.id = id  
  4.    ...:         self.name = name  
  5.    ...:     def __repr__(self):  
  6.    ...:         return 'id = '+self.id +', name = '+self.name  
  7.   
  8. In [2]: xiaoming = Student(id='001',name='xiaoming')  
  9. In [3]: hasattr(xiaoming,'name')  
  10. Out[3]: True  
  11.   
  12. In [4]: hasattr(xiaoming,'address')  
  13. Out[4]: False
41 对象门牌号

返回对象的内存地址

  1. In [1]: id(xiaoming)  
  2. Out[1]: 98234208
42 isinstance

判断_object_是否为类_classinfo_的实例,是返回true

  1. In [1]: class Student():  
  2.    ...:     def __init__(self,id,name):  
  3.    ...:         self.id = id  
  4.    ...:         self.name = name  
  5.    ...:     def __repr__(self):  
  6.    ...:         return 'id = '+self.id +', name = '+self.name  
  7.   
  8. In [2]: xiaoming = Student(id='001',name='xiaoming')  
  9.   
  10. In [3]: isinstance(xiaoming,Student)  
  11. Out[3]: True
43 父子关系鉴定
  1. In [1]: class undergraduate(Student):  
  2.     ...:     def studyClass(self):  
  3.     ...:         pass  
  4.     ...:     def attendActivity(self):  
  5.     ...:         pass  
  6.   
  7. In [2]: issubclass(undergraduate,Student)  
  8. Out[2]: True  
  9.   
  10. In [3]: issubclass(object,Student)  
  11. Out[3]: False  
  12.   
  13. In [4]: issubclass(Student,object)  
  14. Out[4]: True

如果class是classinfo元组中某个元素的子类,也会返回True

  1. In [1]: issubclass(int,(int,float))  
  2. Out[1]: True
44 所有对象之根

object 是所有类的基类

  1. In [1]: o = object()  
  2.   
  3. In [2]: type(o)  
  4. Out[2]: object
45 创建属性的两种方式

返回 property 属性,典型的用法:

  1. class C:  
  2.     def __init__(self):  
  3.         self._x = None  
  4.   
  5.     def getx(self):  
  6.         return self._x  
  7.   
  8.     def setx(self, value):  
  9.         self._x = value  
  10.   
  11.     def delx(self):  
  12.         del self._x  
  13.     # 使用property类创建 property 属性  
  14.     x = property(getx, setx, delx, "I'm the 'x' property.")

使用python装饰器,实现与上完全一样的效果代码:

  1. class C:  
  2.     def __init__(self):  
  3.         self._x = None  
  4.   
  5.     @property  
  6.     def x(self):  
  7.         return self._x  
  8.   
  9.     @x.setter  
  10.     def x(self, value):  
  11.         self._x = value  
  12.   
  13.     @x.deleter  
  14.     def x(self):  
  15.         del self._x
46 查看对象类型

class type(namebasesdict)

传入一个参数时,返回 object 的类型:

  1. In [1]: class Student():  
  2.    ...:     def __init__(self,id,name):  
  3.    ...:         self.id = id  
  4.    ...:         self.name = name  
  5.    ...:     def __repr__(self):  
  6.    ...:         return 'id = '+self.id +', name = '+self.name  
  7.    ...:  
  8.   
  9. In [2]: xiaoming = Student(id='001',name='xiaoming')  
  10. In [3]: type(xiaoming)  
  11. Out[3]: __main__.Student  
  12.   
  13. In [4]: type(tuple())  
  14. Out[4]: tuple
47 元类

xiaoming, xiaohong, xiaozhang 都是学生,这类群体叫做 Student.

Python 定义类的常见方法,使用关键字 class

  1. In [36]: class Student(object):  
  2.     ...:     pass

xiaoming, xiaohong, xiaozhang 是类的实例,则:

  1. xiaoming = Student()  
  2. xiaohong = Student()  
  3. xiaozhang = Student()

创建后,xiaoming 的 __class__ 属性,返回的便是 Student类

  1. In [38]: xiaoming.__class__  
  2. Out[38]: __main__.Student

问题在于,Student 类有 __class__属性,如果有,返回的又是什么?

  1. In [39]: xiaoming.__class__.__class__  
  2. Out[39]: type

哇,程序没报错,返回 type

那么,我们不妨猜测:Student 类,类型就是 type

换句话说,Student类就是一个对象,它的类型就是 type

所以,Python 中一切皆对象,类也是对象

Python 中,将描述 Student 类的类被称为:元类。

按照此逻辑延伸,描述元类的类被称为:_元元类_,开玩笑了~ 描述元类的类也被称为元类。

聪明的朋友会问了,既然 Student 类可创建实例,那么 type 类可创建实例吗?如果能,它创建的实例就叫:类 了。你们真聪明!

说对了,type 类一定能创建实例,比如 Student 类了。

  1. In [40]: Student = type('Student',(),{})  
  2.   
  3. In [41]: Student  
  4. Out[41]: __main__.Student

它与使用 class 关键字创建的 Student 类一模一样。

Python 的类,因为又是对象,所以和 xiaoming,xiaohong 对象操作相似。支持:

  • 赋值

  • 拷贝

  • 添加属性

  • 作为函数参数

  1. In [43]: StudentMirror = Student # 类直接赋值 # 类直接赋值  
  2. In [44]: Student.class_property = 'class_property' # 添加类属性  
  3. In [46]: hasattr(Student, 'class_property')  
  4. Out[46]: True

元类,确实使用不是那么多,也许先了解这些,就能应付一些场合。就连 Python 界的领袖 Tim Peters 都说:

“元类就是深度的魔法,99%的用户应该根本不必为此操心。

六、工具

48 枚举对象

返回一个可以枚举的对象,该对象的next()方法将返回一个元组。

  1. In [1]: s = ["a","b","c"]  
  2.     ...: for i ,v in enumerate(s,1):  
  3.     ...:     print(i,v)  
  4.     ...:  
  5. 1 a  
  6. 2 b  
  7. 3 c
49 查看变量所占字节数
  1. In [1]: import sys  
  2.   
  3. In [2]: a = {'a':1,'b':2.0}  
  4.   
  5. In [3]: sys.getsizeof(a) # 占用240个字节  
  6. Out[3]: 240
50 过滤器

在函数中设定过滤条件,迭代元素,保留返回值为True的元素:

  1. In [1]: fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])  
  2.   
  3. In [2]: list(fil)  
  4. Out[2]: [114513]
51 返回对象的哈希值

返回对象的哈希值,值得注意的是自定义的实例都是可哈希的,list, dict, set等可变对象都是不可哈希的(unhashable)

  1. In [1]: hash(xiaoming)  
  2. Out[1]: 6139638  
  3.   
  4. In [2]: hash([1,2,3])  
  5. # TypeError: unhashable type'list'
52 一键帮助

返回对象的帮助文档

  1. In [1]: help(xiaoming)  
  2. Help on Student in module __main__ object:  
  3.   
  4. class Student(builtins.object)  
  5.  |  Methods defined here:  
  6.  |  
  7.  |  __init__(self, id, name)  
  8.  |  
  9.  |  __repr__(self)  
  10.  |  
  11.  |  Data deors defined here:  
  12.  |  
  13.  |  __dict__  
  14.  |      dictionary for instance variables (if defined)  
  15.  |  
  16.  |  __weakref__  
  17.  |      list of weak references to the object (if defined)

53  获取用户输入

获取用户输入内容

  1. In [1]: input()  
  2. aa  
  3. Out[1]: 'aa'
54 创建迭代器类型

使用iter(obj, sentinel), 返回一个可迭代对象, sentinel可省略(一旦迭代到此元素,立即终止)

  1. In [1]: lst = [1,3,5]  
  2.   
  3. In [2]: for i in iter(lst):  
  4.     ...:     print(i)  
  5.     ...:  
  6. 1  
  7. 3  
  8. 5
  1. In [1]: class TestIter(object):  
  2.     ...:     def __init__(self):  
  3.     ...:         self.l=[1,3,2,3,4,5]  
  4.     ...:         self.i=iter(self.l)  
  5.     ...:     def __call__(self):  #定义了__call__方法的类的实例是可调用的  
  6.     ...:         item = next(self.i)  
  7.     ...:         print ("__call__ is called,fowhich would return",item)  
  8.     ...:         return item  
  9.     ...:     def __iter__(self): #支持迭代协议(即定义有__iter__()函数)  
  10.     ...:         print ("__iter__ is called!!")  
  11.     ...:         return iter(self.l)  
  12. In [2]: t = TestIter()  
  13. In [3]: t() # 因为实现了__call__,所以t实例能被调用  
  14. __call__ is called,which would return 1  
  15. Out[3]: 1  
  16.   
  17. In [4]: for e in TestIter(): # 因为实现了__iter__方法,所以t能被迭代  
  18.     ...:     print(e)  
  19.     ...:  
  20. __iter__ is called!!  
  21. 1  
  22. 3  
  23. 2  
  24. 3  
  25. 4  
  26. 5
55 打开文件

返回文件对象

  1. In [1]: fo = open('D:/a.txt',mode='r', encoding='utf-8')  
  2.   
  3. In [2]: fo.read()  
  4. Out[2]: '\ufefflife is not so long,\nI use Python to play.'

mode取值表:

16d076004f9cee649de23440fc6a1f48.png
56 创建range序列
  1. range(stop)

  2. range(start, stop[,step])

生成一个不可变序列:

  1. In [1]: range(11)  
  2. Out[1]: range(011)  
  3.   
  4. In [2]: range(0,11,1)  
  5. Out[2]: range(011)
57 反向迭代器
  1. In [1]: rev = reversed([1,4,2,3,1])  
  2.   
  3. In [2]: for i in rev:  
  4.      ...:     print(i)  
  5.      ...:  
  6. 1  
  7. 3  
  8. 2  
  9. 4  
  10. 1
58 聚合迭代器

创建一个聚合了来自每个可迭代对象中的元素的迭代器:

  1. In [1]: x = [3,2,1]  
  2. In [2]: y = [4,5,6]  
  3. In [3]: list(zip(y,x))  
  4. Out[3]: [(43), (52), (61)]  
  5.   
  6. In [4]: a = range(5)  
  7. In [5]: b = list('abcde')  
  8. In [6]: b  
  9. Out[6]: ['a''b''c''d''e']  
  10. In [7]: [str(y) + str(x) for x,y in zip(a,b)]  
  11. Out[7]: ['a0''b1''c2''d3''e4']
59 链式操作
  1. from operator import (add, sub)  
  2.   
  3.   
  4. def add_or_sub(a, b, oper):  
  5.     return (add if oper == '+' else sub)(a, b)  
  6.   
  7.   
  8. add_or_sub(12'-')  # -1
60 对象序列化

对象序列化,是指将内存中的对象转化为可存储或传输的过程。很多场景,直接一个类对象,传输不方便。

但是,当对象序列化后,就会更加方便,因为约定俗成的,接口间的调用或者发起的 web 请求,一般使用 json 串传输。

实际使用中,一般对类对象序列化。先创建一个 Student 类型,并创建两个实例。

  1. class Student():  
  2.     def __init__(self,**args):  
  3.         self.ids = args['ids']  
  4.         self.name = args['name']  
  5.         self.address = args['address']  
  6. xiaoming = Student(ids = 1,name = 'xiaoming',address = '北京')  
  7. xiaohong = Student(ids = 2,name = 'xiaohong',address = '南京')

导入 json 模块,调用 dump 方法,就会将列表对象 [xiaoming,xiaohong],序列化到文件 json.txt 中。

  1. import json  
  2.   
  3. with open('json.txt''w') as f:  
  4.     json.dump([xiaoming,xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2, sort_keys=True)

生成的文件内容,如下:

  1. [  
  2.     {  
  3.         "address":"北京",  
  4.         "ids":1,  
  5.         "name":"xiaoming"  
  6.     },  
  7.     {  
  8.         "address":"南京",  
  9.         "ids":2,  
  10.         "name":"xiaohong"  
  11.     }  
  12. ]

14d823c688adbf0dcfd9250d939d3bad.gif

3e4cdde231faeaad8bc912d1324a8300.png

往期回顾

AI卷到艺术界了,DALL·E将战胜人类?

Pandas 与 SQL 的超强结合,爆赞!

云上风景虽好,但不要盲目跟风!

Python 字符串深度总结

  1. 分享
  2. 点收藏
  3. 点点赞
  4. 点在看
标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索