当前位置:   article > 正文

52个python基础代码,你全都知道吗?_python基础代码大全

python基础代码大全

Hello,大家好,我是程序汪小陈

今天,我将为大家展示python基础小例子,帮助大家加深记忆,列举52个例子,快来看看吧~

1 求绝对值

绝对值或复数的模

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

2 元素都为真

接受一个迭代器,如果迭代器的所有元素都为真,那么返回True,否则返回False

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

3 元素至少一个为真 

接受一个迭代器,如果迭代器里至少有一个元素为真,那么返回True,否则返回False

  1. In [4]: any([0,0,0,[]])
  2. Out[4]: False
  3. In [5]: any([0,0,1])
  4. Out[5]: True

4 ascii展示对象  

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

  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]: print(xiaoming)
  11. id = 001, name = xiaoming
  12. In [4]: ascii(xiaoming)
  13. Out[4]: 'id = 001, name = xiaoming'

5 十转二

十进制转换为二进制

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

6 十转八

十进制转换为八进制

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

7 十转十六

十进制转换为十六进制

  1. In [1]: hex(15)
  2. Out[1]: '0xf'

8 判断是真是假  

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

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

9 字符串转字节  

将一个字符串转换成字节类型

  1. In [1]: s = "apple"
  2. In [2]: bytes(s,encoding='utf-8')
  3. Out[2]: b'apple'

10 转为字符串  

字符类型数值类型等转换为字符串类型

  1. In [1]: i = 100
  2. In [2]: str(i)
  3. Out[2]: '100'

11 是否可调用  

判断对象是否可被调用,能被调用的对象就是一个callable 对象,比如函数 str, int 等都是可被调用的,但是例子4xiaoming实例是不可被调用的:

  1. In [1]: callable(str)
  2. Out[1]: True
  3. In [2]: callable(int)
  4. Out[2]: True
  5. In [3]: xiaoming
  6. Out[3]: id = 001, name = xiaoming
  7. In [4]: callable(xiaoming)
  8. Out[4]: False

如果想让xiaoming能被调用 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. In [3]: t()
  14. I can be called
  15. my name is xiaoming

12 十转ASCII

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

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

13 ASCII转十

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

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

14 静态方法 

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)

15 执行字符串表示的代码

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

  1. In [1]: s = "print('helloworld')"
  2. In [2]: r = compile(s,"<string>", "exec")
  3. In [3]: r
  4. Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
  5. In [4]: exec(r)
  6. helloworld

16 创建复数

创建一个复数

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

17 动态删除属性  

删除对象的属性

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

18 转为字典  

创建数据字典

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

19 一键查看对象所有方法 

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

  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. 'name']

20 取商和余数  

分别取商和余数

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

21 枚举对象  

返回一个可以枚举的对象,该对象的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

22 计算表达式

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

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

23 查看变量所占字节数

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

24 过滤器  

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

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

25 转为浮点类型 

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

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

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

  1. In [2]: float('a')
  2. ValueError Traceback (most recent call last)
  3. <ipython-input-11-99859da4e72c> in <module>()
  4. ----> 1 float('a')
  5. ValueError: could not convert string to float: 'a'

26 字符串格式化 

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

  1. In [104]: print("i am {0},age{1}".format("tom",18))
  2. 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)

27 冻结集合  

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

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

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

28 动态获取对象属性 

获取对象的属性

  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. In [2]: xiaoming = Student(id='001',name='xiaoming')
  8. In [3]: getattr(xiaoming,'name') # 获取xiaoming这个实例的name属性值
  9. Out[3]: 'xiaoming'

29 对象是否有这个属性

  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. In [2]: xiaoming = Student(id='001',name='xiaoming')
  8. In [3]: hasattr(xiaoming,'name')
  9. Out[3]: True
  10. In [4]: hasattr(xiaoming,'address')

30 返回对象的哈希值  

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

  1. In [1]: hash(xiaoming)
  2. Out[1]: 6139638
  3. In [2]: hash([1,2,3])
  4. TypeError Traceback (most recent call last)
  5. <ipython-input-32-fb5b1b1d9906> in <module>()
  6. ----> 1 hash([1,2,3])
  7. TypeError: unhashable type: 'list'

31 一键帮助 

返回对象的帮助文档

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

32 对象门牌号 

返回对象的内存地址

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

33 获取用户输入 

获取用户输入内容

  1. In [1]: input()
  2. aa
  3. Out[1]: 'aa'

34 转为整型  

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

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

35 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. In [2]: xiaoming = Student(id='001',name='xiaoming')
  8. In [3]: isinstance(xiaoming,Student)
  9. Out[3]: True

36 父子关系鉴定

  1. In [1]: class undergraduate(Student):
  2. ...: def studyClass(self):
  3. ...: pass
  4. ...: def attendActivity(self):
  5. ...: pass
  6. In [2]: issubclass(undergraduate,Student)
  7. Out[2]: True
  8. In [3]: issubclass(object,Student)
  9. Out[3]: False
  10. In [4]: issubclass(Student,object)
  11. Out[4]: True

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

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

37 创建迭代器类型

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

  1. In [1]: lst = [1,3,5]
  2. In [2]: for i in iter(lst):
  3. ...: print(i)
  4. ...:
  5. 1
  6. 3
  7. 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. In [4]: for e in TestIter(): # 因为实现了__iter__方法,所以t能被迭代
  17. ...: print(e)
  18. ...:
  19. __iter__ is called!!
  20. 1
  21. 3
  22. 2
  23. 3
  24. 4
  25. 5

38 所有对象之根

object 是所有类的基类

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

39 打开文件

返回文件对象

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

mode取值表:

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

40 次幂

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

  1. In [1]: pow(3, 2, 4)
  2. Out[1]: 1

41 打印

  1. In [5]: lst = [1,3,5]
  2. In [6]: print(lst)
  3. [1, 3, 5]
  4. In [7]: print(f'lst: {lst}')
  5. lst: [1, 3, 5]
  6. In [8]: print('lst:{}'.format(lst))
  7. lst:[1, 3, 5]
  8. In [9]: print('lst:',lst)
  9. lst: [1, 3, 5]

42 创建属性的两种方式

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

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

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

  1. class C:
  2. def __init__(self):
  3. self._x = None
  4. @property
  5. def x(self):
  6. return self._x
  7. @x.setter
  8. def x(self, value):
  9. self._x = value
  10. @x.deleter
  11. def x(self):
  12. del self._x

43 创建range序列

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

生成一个不可变序列:

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

44 反向迭代器

  1. In [1]: rev = reversed([1,4,2,3,1])
  2. In [2]: for i in rev:
  3. ...: print(i)
  4. ...:
  5. 1
  6. 3
  7. 2
  8. 4
  9. 1

45 四舍五入

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

  1. In [11]: round(10.0222222, 3)
  2. Out[11]: 10.022
  3. In [12]: round(10.05,1)
  4. Out[12]: 10.1

46 转为集合类型

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

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

47 转为切片对象

class slice(start, stop[, step])

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

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

48 拿来就用的排序函数

排序:

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

49 求和函数

求和:

  1. In [181]: a = [1,4,2,3,1]
  2. In [182]: sum(a)
  3. Out[182]: 11
  4. In [185]: sum(a,10) #求和的初始值为10
  5. Out[185]: 21

50 转元组

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]: (1, 3, 5)

51 查看对象类型

class type(name, bases, dict)

传入一个参数时,返回 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. In [4]: type(tuple())
  13. Out[4]: tuple

52 聚合迭代器

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

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


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/203555?site
推荐阅读
相关标签
  

闽ICP备14008679号