首页 > 数据库 > 数据库开发技术 > ?推荐几个好用的python内置函数
大家好,我是才哥。
今天带大家了解下几个好用的python内置函数,也许在你的coding过程中可以带来不小的便利哦!
目录:
1. 数学运算
2. 进制转义
3. 编码转义
4. 字符串相关
5. 迭代相关
附录(全部内置函数)
加减乘除等等这里就不介绍了,只介绍一个四舍五入的round
round()
用于返回参数四舍五入后的结果
>>> round(12.54)
13
>>> round(12.54,1) # 返回小数点后1位
12.5
bin()oct()hex()>>> bin(8)
'0b1000'
>>> oct(8)
'0o10'
>>> hex(8)
'0x8'
>>> chr(101)
'e'
>>> ord('e')
101
eval()
参数是一个python表达式字符串,返回的是该字符串的求值结果
>>> x = 1
>>> eval('x+1')
2
>>> eval('{"a":1,"b":2}') # 比如参数是一个字符串,字符串表达式的值是一个字典
{'a': 1, 'b': 2}
exec()
参数是一个python语句字符串,无返回值,只是执行该语句
>>> exec('sum = 2+8')
>>> sum
10
enumerate()
返回一个枚举对象,参数必须是一个序列(如列表等)
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> for i , season in enumerate(seasons):
... print(i,season)
...
0 Spring
1 Summer
2 Fall
3 Winter
reversed()
用于返回可迭代对象的反向迭代器
>>> numList = [1,2,3,4]
>>> reversed(numList)
<list_reverseiterator object at 0x00000186E1C63850>
>>> list(_)
[4, 3, 2, 1]
map(function, iterable, ...)
返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器
>>> p = map(lambda x: x*x,[1,2,3,4,5,6,7,8,9,10])
>>> list(p)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
sorted(iterable, *, key=None, reverse=False)
key=str.lower), 默认值为 None (直接比较元素)True,则每个列表元素将按反向顺序比较进行排序>>> sorted([1,3,2,8,7,9])
[1, 2, 3, 7, 8, 9]
>>> tupleList = [(1,2),(3,3),(2,6),(4,1)]
>>> sorted(tupleList, key = lambda x : x[-1]) # 按照列表中每个元素的第2个值排序
[(4, 1), (1, 2), (3, 3), (2, 6)]
filter(function, iterable)
None ,则会假设它是一个身份函数,即 iterable 中所有返回假的元素会被移除>>> list(filter(lambda x : x>10, [1,3,5,7,9,11,13,15,17,19]))
[11, 13, 15, 17, 19]
>>> list(filter(None, [0,1,3,5,0,2,4,6]))
[1, 3, 5, 2, 4, 6]
zip(*iterables)
创建一个聚合了来自每个可迭代对象中的元素的迭代器
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zip(x,y)) #zip() 与 * 运算符相结合可以用来拆解一个列表
<zip object at 0x00000186E24E6D80>
>>> x1,y1 = zip(*zip(x,y))
>>> x1
(1, 2, 3)
>>> list(x1)
[1, 2, 3]
>>> list(y1)
[4, 5, 6]
以下是全部69个内置函数,更多详情大家可以查询python官方文档了解!
| 内置函数 | ||||
|---|---|---|---|---|
abs() |
delattr() |
hash() |
memoryview() |
set() |
all() |
dict() |
help() |
min() |
setattr() |
any() |
dir() |
hex() |
next() |
slice() |
ascii() |
divmod() |
id() |
object() |
sorted() |
bin() |
enumerate() |
input() |
oct() |
staticmethod() |
bool() |
eval() |
int() |
open() |
str() |
breakpoint() |
exec() |
isinstance() |
ord() |
sum() |
bytearray() |
filter() |
issubclass() |
pow() |
super() |
bytes() |
float() |
iter() |
print() |
tuple() |
callable() |
format() |
len() |
property() |
type() |
chr() |
frozenset() |
list() |
range() |
vars() |
classmethod() |
getattr() |
locals() |
repr() |
zip() |
compile() |
globals() |
map() |
reversed() |
__import__() |
complex() |
hasattr() |
max() |
round() |
python内置函数官方文档:
https://docs.python.org/zh-cn/3/library/functions.html--推荐阅读--
③ 用python绘制北京近一年来空气质量热力图,看看北京的沙尘暴真的多吗?
④ 我又用Python爬取了4000+股票数据,并用plotly绘制了树状热力图(treemap)
⑤【推荐收藏】介绍2种Python绘制词云的手法,你会偷偷pick谁呢?
原文作者:可以叫我才哥;如有侵权,请联系管理员删除。