zl程序教程

您现在的位置是:首页 >  Python

当前栏目

python基础_日常高频用法

2023-03-14 09:50:52 时间

一、 数字

1 求绝对值

In [1]: abs(-6)
Out[1]: 6

2 进制转化

十进制转换为二进制
In [2]: bin(10)
Out[2]: '0b1010'
十进制转换为八进制
In [3]: oct(9)
Out[3]: '0o11'
十进制转换为十六进制
In [4]: hex(15)
Out[4]: '0xf'

 

3 整数和ASCII互转

十进制整数对应的ASCII字符 
In [2]: chr(65)
Out[2]: 'A'
 查看某个ASCII字符对应的十进制数
In [2]: ord('A')
Out[2]: 65

4 元素都为真检查

In [5]: all([1,0,3,6])
Out[5]: False
In [6]: all([1,2,3])
Out[6]: True

5 元素至少一个为真检查 

In [7]: any([0,0,0,[]])
Out[7]: False
In [8]: any([0,0,1])
Out[8]: True

6 判断是真是假  

In [9]: bool([0,0,0])
Out[9]: True

In [10]: bool([])
Out[10]: False

In [11]: bool([1,0,1])
Out[11]: True

7 创建复数

In [1]: complex(1,2)
Out[1]: (1+2j)

8 取商和余数  

In [1]: divmod(10,3)
Out[1]: (3, 1)

9 转为浮点类型 

将一个整数或数值型字符串转换为浮点数
In [1]: float(3)
Out[1]: 3.0
如果不能转化为浮点数,则会报ValueError
In [2]: float('a')
# ValueError: could not convert string to float: 'a'

 

10 转为整型  

In [1]: int('12',16)  # 16进制的12转化为十进制
Out[1]: 18

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

In [1]: pow(3, 2, 4)   # 3的2次方 除以4取余
Out[1]: 1

12 四舍五入

In [11]: round(10.0222222, 3)
Out[11]: 10.022

In [12]: round(10.05,1)
Out[12]: 10.1

13 链式比较

i = 3
print(1 < i < 3) # False
print(1 < i <= 3) # True

二、 字符串

14 字符串转字节  

In [12]: s = "apple"                                                            
In [13]: bytes(s,encoding='utf-8')
Out[13]: b'apple'

15 任意对象转为字符串  

In [14]: i = 100                                                                
In [15]: str(i)
Out[15]: '100'
In [16]: str([])
Out[16]: '[]'
In [17]: str(tuple())
Out[17]: '()'

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

In [1]: s  = "print('helloworld')"
In [2]: r = compile(s,"<string>", "exec") # s编译为字节代码对象,<string>为传递的可辨认信息,
exec为编译代码种类
In [3]: r
Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
In [4]: exec(r)
helloworld

17 计算表达式

In [1]: s = "1 + 3 +5"
...: eval(s)
...:
Out[1]: 9

18 字符串格式化 

In [1]: print("i am {0},age{1}".format("tom",18))
Out[1]: i am tom,age18
3.1415926{:.2f}3.14保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
18 {:>10d} ' 18' 右对齐 (默认, 宽度为10)
18 {:<10d} '18 ' 左对齐 (宽度为10)
18 {:^10d} ' 18 ' 中间对齐 (宽度为10)

 

三、 函数

19 排序函数

In [1]: a = [1,4,2,3,1]
In [2]: sorted(a,reverse=True)
Out[2]: [4, 3, 2, 1, 1]
In [3]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'
...: xiaohong','age':20,'gender':'female'}]
In [4]: sorted(a,key=lambda x: x['age'],reverse=False)
Out[4]: [{'name': 'xiaoming', 'age': 18, 'gender': 'male'},
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]

20 求和函数

In [181]: a = [1,4,2,3,1]
In [182]: sum(a)
Out[182]: 11
In [185]: sum(a,10)
Out[185]: 21

23 交换两元素

def swap(a, b):
return b, a
print(swap(1, 0)) # (0,1)

24 操作函数对象

In [31]: def f():
...: print('i\'m f')
...:
In [32]: def g():
...: print('i\'m g')
...:
In [33]: [f,g][1]() #如果是[f,g][0](),返回i'm f
i'm g

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

25 生成逆序序列

list(range(10,-1,-1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 从大到小的排列必须用-1控制

四、 数据结构

29 转为字典  

In [1]: dict()
Out[1]: {}
In [2]: dict(a='a',b='b')
Out[2]: {'a': 'a', 'b': 'b'}
In [3]: dict(zip(['a','b'],[1,2]))
Out[3]: {'a': 1, 'b': 2}
In [4]: dict([('a',1),('b',2)])
Out[4]: {'a': 1, 'b': 2}

30 冻结集合  

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

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

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

31 转为set集合类型

In [159]: a = [1,4,2,3,1]
In [160]: set(a)
Out[160]: {1, 2, 3, 4}

32 转为切片对象

class slice(start, stop[, step])

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

In [1]: a = [1,4,2,3,1]
In [2]: my_slice_meaning = slice(0,5,2)
In [3]: a[my_slice_meaning]
Out[3]: [1, 2, 1]

33 转元组

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

五、 类和对象

34 是否可调用  

In [1]: callable(str)
Out[1]: True
In [2]: callable(int)
Out[2]: True
In [18]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name

In [19]: xiaoming = Student('001','xiaoming')
In [20]: callable(xiaoming)
Out[20]: False #不可调用

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

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: def __call__(self):
...: print('I can be called')
...: print(f'my name is {self.name}')
...:

In [2]: t = Student('001','xiaoming')
In [3]: t()
I can be called
my name is xiaoming

35 ascii 展示对象  

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

>>> class Student():
def __init__(self,id,name):
self.id = id
self.name = name
def __repr__(self):
return 'id = '+self.id +', name = '+self.name

调用:

>>> xiaoming = Student(id='1',name='xiaoming')
>>> xiaoming
id = 1, name = xiaoming
>>> ascii(xiaoming)
'id = 1, name = xiaoming'

36 类方法 

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

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: @classmethod
...: def f(cls):
...: print(cls)

37 动态删除属性  

In [1]: delattr(xiaoming,'id')
In [2]: hasattr(xiaoming,'id')
Out[2]: False

38 一键查看对象所有方法 

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

In [96]: dir(xiaoming)
Out[96]:
['__class__',
'__dir__',
'__doc__',
'name']

39 动态获取对象属性 

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: getattr(xiaoming,'name') # 获取xiaoming这个实例的name属性值
Out[3]: 'xiaoming'

40 对象是否有这个属性

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: hasattr(xiaoming,'name')
Out[3]: True
In [4]: hasattr(xiaoming,'address')
Out[4]: False

41 对象内存地址

In [1]: id(xiaoming)
Out[1]: 98234208

42 isinstance

判断object是否为类classinfo的实例,是返回true

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: isinstance(xiaoming,Student)
Out[3]: True

43 父子关系鉴定

In [1]: class undergraduate(Student):
...: def studyClass(self):
...: pass
...: def attendActivity(self):
...: pass
In [2]: issubclass(undergraduate,Student)
Out[2]: True
In [3]: issubclass(object,Student)
Out[3]: False
In [4]: issubclass(Student,object)
Out[4]: True

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

In [1]: issubclass(int,(int,float))
Out[1]: True

44 所有对象之根

object 是所有类的基类

In [1]: o = object()
In [2]: type(o)
Out[2]: object

46 查看对象类型

class type(name, bases, dict)

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

In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...:

In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: type(xiaoming)
Out[3]: __main__.Student
In [4]: type(tuple())
Out[4]: tuple

六、工具

48 枚举对象  

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

In [1]: s = ["a","b","c"]
...: for i ,v in enumerate(s,1):
...: print(i,v)
...:
1 a
2 b
3 c

49 查看变量所占字节数

In [1]: import sys
In [2]: a = {'a':1,'b':2.0}
In [3]: sys.getsizeof(a) # 占用240个字节
Out[3]: 240

50 过滤器  

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

In [1]: fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])
In [2]: list(fil)
Out[2]: [11, 45, 13]

51 返回对象的哈希值  

自定义的实例都是可哈希的,listdictset等可变对象都是不可哈希的(unhashable)

In [1]: hash(xiaoming)
Out[1]: 6139638
In [2]: hash([1,2,3]) # TypeError: unhashable type: 'list'

52 一键帮助 

In [1]: help(xiaoming)
Help on Student in module __main__ object:
class Student(builtins.object)
| Methods defined here:
|
| __init__(self, id, name)
|
| __repr__(self)
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)

53 获取用户输入 

In [1]: input()
aa
Out[1]: 'aa'

54 创建迭代器类型

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

In [1]: lst = [1,3,5]
In [2]: for i in iter(lst):
...: print(i)
...:
1
3
5
In [1]: class TestIter(object):
...: def __init__(self):
...: self.l=[1,3,2,3,4,5]
...: self
.i=iter(self.l)
...: def __call__(self): #定义了__call__方法的类的实例是可调用的
...: item = next(self.i)
...: print ("__call__ is called,fowhich would return",item)
...: return item
...: def __iter__(self): #支持迭代协议(即定义有__iter__()函数)
...: print ("__iter__ is called!!")
...: return iter(self.l)
In [2]: t = TestIter()
In [3]: t() # 因为实现了__call__,所以t实例能被调用
__call__ is called,which would return 1
Out[3]: 1
In [4]: for e in TestIter(): # 因为实现了__iter__方法,所以t能被迭代
...: print(e)
...:
__iter__ is called!!
1
3
2
3
4
5

55 打开文件

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

mode取值表:

字符意义
'r' 读取(默认)
'w' 写入,并先截断文件
'x' 排它性创建,如果文件已存在则失败
'a' 写入,如果文件存在则在末尾追加
'b' 二进制模式
't' 文本模式(默认)
'+' 打开用于更新(读取与写入)

 

56 创建range序列

  1. range(stop)

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

生成一个不可变序列:

In [1]: range(11)
Out[1]: range(0, 11)
In [2]: range(0,11,1)
Out[2]: range(0, 11)

57 反向迭代器

In [1]: rev = reversed([1,4,2,3,1])
In [2]: for i in rev:
...: print(i)
1
3
2
4
1

58 聚合迭代器

In [1]: x = [3,2,1]
In [2]: y = [4,5,6]
In [3]: list(zip(y,x))
Out[3]: [(4, 3), (5, 2), (6, 1)]
In [4]: a = range(5)
In [5]: b = list('abcde')
In [6]: b
Out[6]: ['a', 'b', 'c', 'd', 'e']
In [7]: [str(y) + str(x) for x,y in zip(a,b)]
Out[7]: ['a0', 'b1', 'c2', 'd3', 'e4']

59 链式操作

from operator import (add, sub)
def add_or_sub(a, b, oper):
return (add if oper == '+' else sub)(a, b)
add_or_sub(1, 2, '-') # -1





 祸大福大,福大祸大。