最近几天都没更新文章了,项目有点小忙,本打算继续更新魔术方法的,发现总结的还没到位,索性先搁置下吧。
今天就聊聊部分内置函数的使用,当然,还有一部分没罗列出来,有兴趣的可去官网详解下哦!!!
abs(x)
描述:
返回一个数的绝对值。 参数可以是整数、浮点数或任何实现了 abs 的对象。 如果参数是一个复数,则返回它的模。
示例说明:
print(abs(-5))
print(abs(2.4+5.6j))
运行结果:
5
6.092618484691126
Process finished with exit code 0
all(iterable)
描述:
如果 iterable 的所有元素均为真值(或可迭代对象为空)则返回 True
示例说明:
print(all([1])) # 真值
print(all([0])) # 非真值
print(all([])) # 可迭代对象为空
print(all('')) # 可迭代对象为空
运行结果:
True
False
True
True
Process finished with exit code 0
上述例子实际就等介于它:
def all_example(iterable):
for i in iterable:
if not i:
return False
return True
print(all_example(''))
运行结果:
True
Process finished with exit code 0
any(iterable)
描述:
如果 iterable 的任一元素为真值则返回 True。 如果可迭代对象为空,返回 False
示例说明:
print(any([0])) # 非真值
print(any([1])) # 为真值
print(any([])) # 可迭代对象为空
print(any('')) # 可迭代对象为空
运行结果:
False
True
False
False
Process finished with exit code 0
从上述示例中可以看到,any
和all
是相对立的。也等价于它:
def any_example(iterable):
for i in iterable:
if i:
return True
return False
print(any_example(''))
运行结果:
False
Process finished with exit code 0
bytes(x)
描述:
返回一个新的“bytes”对象,这是一个不可变序列,字符串支持的方法,它同样也支持
示例说明:
print(bytes(1))
运行结果:
b'\x00'
Process finished with exit code 0
enumerate(iterable, start=0)
描述:
返回一个枚举对象。iterable 必须是一个序列,或其他支持迭代的对象。 enumerate() 返回的是一个元组,里面包含一个计数值(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。
示例说明:
# 创建一个新字典
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1)))
运行结果:
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Process finished with exit code 0
eval(*args, **kwargs)
描述:
这里基本使用介绍:可进行字符串数字的计算和数据类型的自动转换
示例说明:
- 执行计算
# 执行字符串的数字的计算
print(eval('1+2'))
运行结果:
3
Process finished with exit code 0
- 类型自动转换
# 针对类型会自动转换
a, b = 1, '1'
if a == eval(b):
print("成功!")
else:
print("失败")
运行结果:
成功!
Process finished with exit code 0
filter(function, iterable)
描述:
用 iterable 中函数 function 返回真的那些元素,构建一个新的迭代器。iterable 可以是一个序列,一个支持迭代的容器,或一个迭代器。如果 function 是 None ,则会假设它是一个身份函数,即 iterable 中所有返回假的元素会被移除。
示例说明:
def is_f(x):
return x % 2 == 1
new_list = list(filter(is_f, [0, 1, 2, 3, 4, 5]))
print(new_list)
new_list = list(filter(None, [0, 1, 2, 3, 4, 5]))
print(new_list)
运行结果:
[1, 3, 5]
[1, 2, 3, 4, 5]
Process finished with exit code 0
format()
描述:
格式化输出
- {:.2f} 保留小数点后两位
- {:+.2f} 带符号保留小数点后两位
- {:+.2f} 带符号保留小数点后两位
- {:.0f} 不带小数
- {:0>2d} 数字补零 (填充左边, 宽度为2)
- {:x<4d} 数字补x (填充右边, 宽度为4)
- {:x<4d} 数字补x (填充右边, 宽度为4)
- {:,} 以逗号分隔的数字格式
- {:.2%} 百分比格式
- {:.2e} 指数记法
- {:>10d} 右对齐 (默认, 宽度为10)
- {:<10d} 左对齐 (宽度为10)
- {:^10d} 中间对齐 (宽度为10)
示例说明:
a = "你好 {} {}".format("hello", "world")
print(a)
a = "你好 {0} {1} {url}".format("hello", "world", url="www.baidu.com")
print(a)
运行结果:
你好 hello world
你好 hello world www.baidu.com
Process finished with exit code 0
globals()
描述:
返回表示当前全局符号表的字典。是当前模块的字典。
示例说明:
print(globals())
运行结果:
{'__name__': '__main__', '__doc__': '\n注释信息:\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001A9ED494048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:/project_gitee/Test/playwrightProject/models/built_functions.py', '__cached__': None}
Process finished with exit code 0
help()
描述:
启动内置的帮助系统(此函数主要在交互式中使用)。如果没有实参,解释器控制台里会启动交互式帮助系统。如果实参是一个字符串,则在模块、函数、类、方法、关键字或文档主题中搜索该字符串,并在控制台上打印帮助信息。如果实参是其他任意对象,则会生成该对象的帮助页。
示例说明:
print(help(property))
运行结果:
Help on class property in module builtins:
class property(object)
| property(fget=None, fset=None, fdel=None, doc=None)
|
| Property attribute.
|
| fget
| function to be used for getting an attribute value
| fset
| function to be used for setting an attribute value
| fdel
| function to be used for del'ing an attribute
| doc
| docstring
...
....
.....
Process finished with exit code 0
id(object)
描述:
返回对象的“标识值”。就理解成是这个对象的门牌号
示例说明:
a = 1
print(id(a))
运行结果:
140724420639808
Process finished with exit code 0
input()
描述:
控制台输入
示例说明:
a = input("请输入数据>>:")
print(a)
运行结果:
请输入数据>>: 1
1
Process finished with exit code 0
isinstance(object, classinfo)
描述:
检测对象的数据类型是不是指定的那样,classinfo就是类型,可以是str,list,dict,tuple,int,float等
示例说明:
a = 1
if isinstance(a, str):
print(a)
else:
print(type(a))
运行结果:
<class 'int'>
Process finished with exit code 0
len(s)
描述:
返回对象的长度(元素个数)。实参可以是序列(如 string、bytes、tuple、list 或 range 等)或集合(如 dictionary、set 或 frozen set 等)。
示例说明:
a = [1,2,3]
print(len(a))
运行结果:
3
Process finished with exit code 0
max()和min()
描述:
返回可迭代对象中最大的元素,或者返回两个及以上实参中最大的。
返回可迭代对象中最小的元素,或者返回两个及以上实参中最小的。\
示例说明:
print(max([1, 2]))
print(max([1, 2], [2, 3]))
print(min([1, 2]))
print(min([1, 2], [2, 3]))
运行结果:
2
[2, 3]
1
[1, 2]
Process finished with exit code 0
map(function, iterable, …)
描述:
返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器。
示例说明:
def map_example(x):
return x % 2 == 1
print(list(map(map_example, [1, 2, 3, 4, 5])))
运行结果:
[True, False, True, False, True]
Process finished with exit code 0
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
描述:
打开 file 并返回对应的 file object。 如果该文件不能被打开,则引发 OSError。 请参阅 读写文件 获取此函数的更多用法示例。
示例说明:
with open(file="xxx.text", mode="r", encoding="utf-8") as f:
f.read()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
描述:
将 objects 打印输出至 file 指定的文本流,以 sep 分隔并在末尾加上 end。 sep 、 end 、 file 和 flush 必须以关键字参数的形式给出。
示例说明:
- 指定
end
,是不换行
print("hello world", "你好", end="")
运行结果:
hello world 你好-
Process finished with exit code 0
- 不指定
end
,是不换行
print("hello world", "你好")
运行结果:
hello world 你好
Process finished with exit code 0
property(fget=None, fset=None, fdel=None, doc=None)
描述:
返回 property 属性。
fget 是获取属性值的函数。 fset 是用于设置属性值的函数。 fdel 是用于删除属性值的函数。并且 doc 为属性对象创建文档字符串
示例说明:
class C:
def __init__(self):
self._x = 1
def cc(self):
return self._x
x = property(fget=cc, doc="I'm the 'x' property.")
if __name__ == '__main__':
c = C()
print(c.x)
运行结果:
1
Process finished with exit code 0
也阔以这样使用:
class C:
def __init__(self):
self._x = 1
@property
def cc(self):
return self._x
if __name__ == '__main__':
c = C()
print(c.cc)
运行结果:
1
Process finished with exit code 0
range(start, stop[, step])
描述:
函数返回的是一个可迭代对象(类型是对象
- start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
- stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
- step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
示例说明:
for i in range(1, 15, 2):
print(i)
运行结果:
1
3
5
7
9
11
13
Process finished with exit code 0
reversed(seq)
描述:
返回一个反向的 iterator。
示例说明:
print(list(reversed([1, 2, 3, 4, 5, 6])))
运行结果:
[6, 5, 4, 3, 2, 1]
Process finished with exit code 0
round(number[, ndigits])
描述:
返回 number 舍入到小数点后 ndigits 位精度的值。 如果 ndigits 被省略或为 None,则返回最接近输入值的整数。
示例说明:
print(round(12.11111, 2))
运行结果:
12.11
Process finished with exit code 0
sorted(iterable, *, key=None, reverse=False)
描述:
根据 iterable 中的项返回一个新的已排序列表。
具有两个可选参数,它们都必须指定为关键字参数。
key 指定带有单个参数的函数,用于从 iterable 的每个元素中提取用于比较的键 (例如 key=str.lower)。 默认值为 None (直接比较元素)。
reverse 为一个布尔值。 如果设为 True,则每个列表元素将按反向顺序比较进行排序。
示例说明:
print(sorted([1, 3, 4, 5, 6, 3, 4, 8]))
print(sorted([1, 3, 4, 5, 6, 3, 4, 8], reverse=True))
print(sorted([('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)], key=lambda s: s[1]))
运行结果:
[1, 3, 3, 4, 4, 5, 6, 8]
[8, 6, 5, 4, 4, 3, 3, 1]
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
Process finished with exit code 0
sum(iterable, start=0)
描述:
从 start 开始自左向右对 iterable 的项求和并返回总计值。 iterable 的项通常为数字,而 start 值则不允许为字符串。
示例说明:
print(sum([1, 2, 3, 4, 5]))
print(sum([1, 2, 3, 4, 5], 2))
运行结果:
15
17
Process finished with exit code 0
type(object)
描述:
传入一个参数时,返回 object 的类型。 返回值是一个 type 对象。
示例说明:
print(type(1))
运行结果:
<class 'int'>
Process finished with exit code 0
zip(*iterables, strict=False)
描述:
在多个迭代器上并行迭代,从每个迭代器返回一个数据项组成元组。
示例说明:
for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
print(item)
运行结果:
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
Process finished with exit code 0
以上总结或许能帮助到你,或许帮助不到你,但还是希望能帮助到你,如有疑问、歧义,直接私信留言会及时修正发布;非常期待你的点赞和分享哟,谢谢!
未完,待续…
一直都在努力,希望您也是!
微信搜索公众号:就用python
文章作者:李 锋|编辑排版:梁莉莉
![](https://img-blog.csdnimg.cn/96187716ada349b88c4f824dc2a4c95b.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiA5ZCN5bCP5rWL6K-V,size_12,color_FFFFFF,t_70,g_se,x_16)