当前位置:
首页 > Python基础教程 >
-
Python_常见内置函数(2)
1 >>> max(1, 2, 3)
2 3
3 >>> max(1, 2, '3')
4 Traceback (most recent call last):
5 File "<pyshell#1>", line 1, in <module>
6 max(1, 2, '3')
7 TypeError: '>' not supported between instances of 'str' and 'int'
8 >>> max(1, 2, '3', key=int)
9 '3'
10 >>> max(-3, 1, 2, key=abs)
11 -3
12 >>> max('123')
13 '3'
14 >>> max([1, 8], [2, 6], [3, 4])
15 [3, 4]
16 >>> couple = ({'name': 'Bunny', 'age': 18, 'salary': 888}, {'name': 'Twan', 'age': 20, 'salary': 666})
17 >>> max(couple, key=lambda x: x['age'])
18 {'name': 'Twan', 'age': 20, 'salary': 666}
19 >>> max((), default=0)
20 0
(5)编码
- bin(number), oct(number), hex(number)
- chr(i), ord(c), ascii(obj), repr(obj)
1 >>> bin(10)
2 '0b1010'
3 >>> oct(10)
4 '0o12'
5 >>> hex(10)
6 '0xa'
7 >>> chr(65)
8 'A'
9 >>> ord('A')
10 65
11 >>> ascii('hello world')
12 "'hello world'"
13 >>> repr('hello world')
14 "'hello world'"
15 >>> ascii('你好,世界')
16 "'\\u4f60\\u597d\\uff0c\\u4e16\\u754c'"
17 >>> repr('你好,世界')
18 "'你好,世界'"
(6)判断
- bool(x), all(iterable), any(iterable), callable(object)
1 >>> all(['a', 'b', 'c'])
2 True
3 >>> all(['a', 'b', '', 'c'])
4 False
5 >>> all([])
6 True
7 >>> any([0, '', False])
8 False
9 >>> any([])
10 False
11 >>> callable(str)
12 True
13 >>> callable('hello world')
14 False
(7)迭代器
- iter(iterable); iter(callable, sentinel)
- next(iterator[, default])
- filter(function or None, iterable)
1 >>> for i in iter(list('abc')):
2 print(i)
3
4 a
5 b
6 c
7
8 >>> from random import randint
9 >>> def guess():
10 return randint(0,10)
11 >>> num = 1
12 >>> for i in iter(guess, 5):
13 print('第%s次猜测,猜测数字为:%s' % (num, i))
14 num += 1
15
16 第1次猜测,猜测数字为:3
17 第2次猜测,猜测数字为:1
注:猜数字的例子来自http://www.imooc.com/article/287997
1 >>> i = iter(list('abc'))
2 >>> next(i)
3 'a'
4 >>> next(i)
5 'b'
6 >>> next(i)
7 'c'
8 >>> next(i)
9 Traceback (most recent call last):
10 File "<pyshell#27>", line 1, in <module>
11 next(i)
12 StopIteration
13 >>> next(i, 0)
14 0
1 >>> def is_odd(n):
2 return n % 2 == 1
3
4 >>> oldlist = [i for i in range(1,11)]
5 >>> oldlist
6 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
7 >>> newlist = list(filter(is_odd, oldlist))
8 >>> newlist
9 [1, 3, 5, 7, 9]
(8)属性操作
- getattr(obj, name[, default])
- setattr(obj, name, value)
- hasattr(obj, name)
- delattr(obj, name)
1 >>> class Person:
2 name = 'Bunny'
3 age = 18
4 sex = '女'
5
6 >>> Person.name
7 'Bunny'
8 >>> Person.country
9 Traceback (most recent call last):
10 File "<pyshell#6>", line 1, in <module>
11 Person.country
12 AttributeError: type object 'Person' has no attribute 'country'
13 >>> getattr(Person, 'age', 0)
14 18
15 >>> getattr(Person, 'country', 0)
16 0
17 >>> setattr(Person, 'country', 'China')
18 >>> getattr(Person, 'country', 0)
19 'China'
20 >>> delattr(Person, 'sex')
21 >>> hasattr(Person, 'sex')
22 False
(9)辅助函数
- dir([object])
1 >>> dir()
2 ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
3 >>> dir(dict)
4 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
- help([object])
1 >>> help(hash)
2 Help on built-in function hash in module builtins:
3
4 hash(obj, /)
5 Return the hash value for the given object.
6
7 Two objects that compare equal must also have the same hash value, but the
8 reverse is not necessarily true.
- hash(obj)
1 >>> hash('hello world')
2 -8331809543453374991
3 >>> hash(tuple('abcde'))
4 5996617995451668254
哈希的相关知识点:https://www.cnblogs.com/abdm-989/p/11329122.html
- id([object])
1 >>> a = 'hello world'
2 >>> b = a
3 >>> id(a)
4 1873301041520
5 >>> id(b)
6 1873301041520
- memoryview(object)
1 >>> a = memoryview(bytearray('abcde', 'utf-8'))
2 >>> a[1]
3 98
4 >>> a[1:3]
5 <memory at 0x0000017F63B83408>
6 >>> a[1:3].tobytes()
7 b'bc'
8 >>> a[1:3].tolist()
9 [98, 99]
优点:memoryview减少内存拷贝,优化效率(详情可参考https://www.hustyx.com/python/222/)
- type(object), type(name, bases, dict)
- issubclass(cls, class_or_tuple)
- isinstance(obj, class_or_tuple)
1 >>> a = 2
2 >>> type(a)
3 <class 'int'>
4 >>> isinstance(a, int)
5 True
6 >>> isinstance(a, str)
7 False
8 >>> isinstance(a, (str, int, list)) # 是元组中的一个就返回True
9 True
1 >>> class A:
2 pass
3
4 >>> class B(A):
5 pass
6
7 >>> issubclass(B, A)
8 True
9 >>> isinstance(B(), A)
10 True
11 >>> type(B()) == A
12 False
(10)面向对象
- @classmethod, @staticmethod
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式