Python学习笔记(十二) Python3 内置函数

【摘要】 史上最为详细的python学习笔记,记录学习过程的知识点和难点

Python3 内置函数

内置函数

abs()

dict()

help()

min()

setattr()&3

all()

dir()

hex()

next()&2

slice()

any()

divmod()

id()

object()

sorted()

ascii()

python2无

enumerate()

input()

oct()

staticmethod()

bin()

eval()

int()

open()

str()

bool()

exec()

比eval()高级

python2为execfile()

isinstance()&5

ord()&1

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

python2无

float()

iter()&2

print()

tuple()

callable()

format()

len()

property()1

property()2

type()&5

chr()&1

frozenset()

list()

range()

vars()&4

classmethod()

getattr()&3

locals()&4

repr()

zip()zip(*)

compile()

globals()&4

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

delattr()

hash()

memoryview()

set()

exec内置表达式

basestring()

python2有

file()

python2有

raw_input()

python2有

unichr()

python2有

reduce()

python2有

unicode()

long()

python2有

reload()

python2有

xrange()

python2有

cmp()

python2有

”’ Python3内置函数”’
# 1abs(x)x–数值表达式,可以是整数,浮点数,复数
# 返回数字的绝对值,

print(‘abs(-40), abs(40))
print(‘abs(100.10), abs(100.10))


# 2all(iterable)iterable-列表或元组
# 用于判断给定的可迭代参数iterable中的所有元素是否都为True,是返回True,否则返回False
# 元素除了0、空、NoneFalse外都算True


”’
函数等价于:
def all(iterable):
for element in iterable:
if not element:
return False
return True
”’

# 注意:空列表、空元组返回值为True


# 3any(iterable)iterable–元组或列表
# 用于判断给定的可迭代参数iterable是否全部为False,是则返回False,如果有一个为True则返回True

”’
函数等价于:
def any(iterable):
for element in iterable:
if element:
return True
return False
”’


# 4ascii(object)object–对象
# 类似于repr()函数,返回一个表示对象的字符串,但是对于字符串中的非ASCII字符则返回通过
# repr()函数使用\x, \u\U编码的字符。生成字符串类似Python2repr()函数的返回值


# 5bin(x)x–int或者long int数字
# 返回一个整数int或者长整数long int的二进制表示


# 6bool(x)x–要进行转换的参数
# 用于将给定参数转换为布尔类型,如果没有参数则返回False
# boolint的子类:issubclass(bool, int) — True


# 7bytearray([source[, encoding[, errors]]])
# 返回一个新字节数组,这个数组里的元素是可变的,并且每个元素的值范围为0 <= x < 256

”’
参数:
如果source为整数,则返回一个长度为source的初始化数组;
如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
如果source为可迭代类型,则元素必须为[0, 255]中的整数;
如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray
如果没有输入任何类型,默认就是初始化数组的0个元素
”’


# 8bytes([source[, encoding[, errors]]])
# 返回一个新的bytes对象,该对象是一个0 <= x < 256区间内的整数不可变序列。它是bytearray的不可变版本

”’
参数:
如果source为整数,则返回一个长度为source的初始化数组;
如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
如果source为可迭代类型,则元素必须为[0, 255]中的整数;
如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray
如果没有输入任何类型,默认就是初始化数组的0个元素
”’


# 9callable(object)
# 用于检查一个对象是否是可调用的。
# 如果返回Trueobject仍然可能调用失败;但如果返回False,调用对象object绝对不会成功
# 对于函数、方法、lambda表达式、类以及实现了__call__方法的类实例,它都返回True


# 10chr(i)i–可以是10进制,也可以是16进制形式的数字,数字范围为01,114,11116进制为0x10FFFF
# 用一个整数作为参数,返回值是当前整数对应的ASCII字符


# 11classmethod修饰符:
”’
描述:
classmethod修饰符对应的函数不需要实例化,不需要self参数,但第一个参数需要是
表示自身类的cls参数,可以来调用类的属性,类的方法,实例化对象等。
语法:
@classmethod
参数:

返回值:
返回函数的类方法

”’
class A(object):
bar = 1
def func1(self):
print(‘foo’)
@classmethod
def func2(cls):
print(‘func2’)
print(cls.bar) # 调用类属性bar
cls().func1() # 调用类方法foo

A.func2() # 不需要实例化
”’
输出结果为:
func2
1
foo
”’


# 12compile(source, filename, mode[, flags[, dont_inherit]])inherit–继承
# 将一个字符串编译为字节代码
# 返回值返回表达式执行结果

”’
参数:
source–字符串或者ASTAbstract Syntax Trees抽象语法树)对象。
filename–代码文件名称,如果不是从文件读取代码,则传递一些可辨认的值。
mode–指定编译代码的种类,可以指定为execevalsingle
flags–变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
flagsdont_inherit是用来控制编译源码时的标志
”’


# 13complex([real[, imag]])real–实数,imag–虚数
# 用于创建一个值为real + imag * j的复数或者转化为一个字符串或数为复数。
# 如果第一个参数为字符串,则不需要指定第二个参数
# 返回值返回一个复数

”’
参数:
real–int, long, float或字符串。
imag–int, long, float
”’


# 14delattr()
”’
描述:
用于删除属性,delattr(x, ‘foobar)相当于del x.foobar
语法:
delattr(object, name)
参数:
object–对象
name–必须是对象的属性
返回值:

”’

class Coordinate:
x = 10
y = –5
z = 0

point1 = Coordinate()
print(‘x = ‘, point1.x)
print(‘y = ‘, point1.y)
print(‘z = ‘, point1.z)

delattr(Coordinate, ‘z’)

print(‘–删除z属性后–‘)
print(‘x = ‘, point1.x)
print(‘y = ‘, point1.y)
# print(‘z = ‘, point1.z) # 报错AttributeError: ‘Coordinate’ object has no attribute ‘z’


# 15dict()
”’
描述:
用于创建一个字典
语法:
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)
参数:
**kwargs–关键字
mapping–元素的容器
iterable–可迭代对象
返回值:
返回一个字典
”’

print(dict()) # 创建空字典
# {}
print(dict(a=‘a’, b=‘b’, t=‘t’)) # 传入参数
# {‘a’: ‘a’, ‘b’: ‘b’, ‘t’: ‘t’}
print(dict(zip([‘one’, ‘two’, ‘three’], [1, 2, 3]))) # 映射函数方式构造字典
# {‘one’: 1, ‘two’: 2, ‘three’: 3}
print(dict([(‘one’, 1), (‘two’, 2), (‘three’, 3)])) # 可迭代对象方式构造字典
# {‘one’: 1, ‘two’: 2, ‘three’: 3}


# 16zip()
”’
描述:
zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的对象,这样做的好处就是节约了不少的内存空间。
我们可以使用list()转换来输出列表。
如果各个迭代器的元素个数不一致,则返回的列表长度与最短的对象相同

利用*号操作,可以将元组解压为列表。

特别提醒:zip()方法在Python2.x中返回的是一个列表。
语法:
zip([iterable, …])
参数:
iterable–一个或多个迭代器
返回值:
返回一个对象
”’

a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b) # 返回一个对象
print(zipped)
# <zip object at 0x000002039CDC1740>
print(list(zipped)) # list()转换为列表
# [(1, 4), (2, 5), (3, 6)]
print(list(zip(a, c))) # 元素个数与最短的列表一致
# [(1, 4), (2, 5), (3, 6)]

a1, a2 = zip(*zip(a, b)) # zip相反,zip(*)可理解为解压,返回二维矩阵式
print(a1)
# (1, 2, 3)
print(list(a2))
# [4, 5, 6]

b1, b2 = zip(*zip(a, c))
print(b1, b2)
# (1, 2, 3) (4, 5, 6)


# 17dir()
”’
描述:
dir()函数不带参数时,以列表形式返回当前范围内的变量、方法和定义的类型;
带参数时,返回参数的属性、方法列表。
如果参数包含方法__dir__(),该方法将被调用,
如果参数不包含方法__dir__(),该方法将最大限度地收集参数信息。
语法:
dir([object])
参数:
object-对象、变量、类型
返回值:
返回模块的属性列表
”’

print(dir()) # 获得当前模块的属性列表
# [‘__annotations__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]

print(dir([])) # 查看列表的方法
# [‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

print(dir(())) # 查看元组的方法
# [‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘count’, ‘index’]
print(dir({})) # 查看字典的方法
# [‘__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__’, ‘__reversed__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘items’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, ‘values’]

print(dir(set())) # 查看集合的方法
# [‘__and__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’, ‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’, ‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’, ‘difference’, ‘difference_update’, ‘discard’, ‘intersection’, ‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’, ‘pop’, ‘remove’, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’, ‘update’]
print(type(set()))
# <class ‘set’>


# 18divmod()
”’
描述:
divmod()函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a//b, a%b)。
Python3.x版本该函数不支持复数
语法:
divmod(a, b)
参数:
a–数字,非复数
b–数字,非复数
如果参数a与参数b都是整数,函数返回的结果相当于(a // b, a % b
如果其中一个参数为浮点数时,函数返回的结果相当于(q, a % b),q通常是math.floor(a / b),但也有可能是比1小,不过q * b + a % b的值会非常接近a
如果a % b 的求余结果不为0 ,则余数的正负符号跟参数b 是一样的,若b 是正数,余数为正数,若b 为负数,余数也为负数,并且0 <= abs(a % b) < abs(b)
”’

print(divmod(7, 2)) # (3, 1)
print(divmod(8, 2)) # (4, 0)
print(divmod(8, 2)) # (-4, 0)
print(divmod(3, 1.3)) # (2.0, 0.3999999999999999)


# 19enumerate()
”’
描述:
enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)
组合为一个索引序列同时列出数据和数据下标,一般用在for循环中
语法:
enumerate(sequence, [start=0])
参数:
sequence–一个序列、迭代器或其他支持迭代对象
start–下标起始位置
返回值:
返回enumerate(枚举)对象
”’

seasons = [‘Spring’, ‘Summer’, ‘Autumn’, ‘Winter’]
print(seasons)
# [‘Spring’, ‘Summer’, ‘Autumn’, ‘Winter’]
print(enumerate(seasons))
# <enumerate object at 0x000001A8AFDFDE40>
print(type(enumerate(seasons)))
# <class ‘enumerate’>
print(list(enumerate(seasons)))
# [(0, ‘Spring’), (1, ‘Summer’), (2, ‘Autumn’), (3, ‘Winter’)]
print(list(enumerate(seasons, start=1)))
# [(1, ‘Spring’), (2, ‘Summer’), (3, ‘Autumn’), (4, ‘Winter’)]

# 普通的for循环
i = 0
seq = [‘one’, ‘two’, ‘three’, ‘four’]
for element in seq:
print(i, seq[i])
i += 1
print(‘—————–‘)
# for循环使用enumerate
seq = [‘one’, ‘two’, ‘three’, ‘four’]
for i, element in enumerate(seq, start=1):
print(i, element)


# 20eval()
”’
描述:
用来执行一个字符串表达式,并返回表达式的值
语法:
eval(expression[, globals[, locals]])
参数:
expression–表达式
globals–变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals–变量作用域,全局命名空间,如果被提供,可以是任何映射对象。
返回值:
返回表达式计算结果
”’

x = 7
print(eval(‘3 * x’))
print(eval(‘pow(2, 2)’))
print(eval(‘2 + 3’))
n = 81
print(eval(‘n + 4’))


# 21exec()
”’
描述:
exec执行存储在字符串或文件中的Python语句,相比于evalexec可以执行更复杂的Python代码
语法:
exec(object[, globals[, locals]])
参数:
object–必选参数,表示需要被执行的Python代码。它必须是字符串或code对象,
如果object是一个字符串,该字符串会先被解析为一组Python语句,然后再执行(除非发生语法错误);
如果object是一个code对象,那么它只是被简单的执行。
globals–可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。
locals–可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象;
如果该参数被忽略,那么它将会取与globals相同的值。
返回值:
exec返回值永远为None
”’

# 单行语句字符串
exec(‘print(“hello world”)’)
# hello world
exec(“print(‘runoob.com’)”)
# runoob.com

# 多行语句字符串
exec(”’for i in range(5):
print(‘iter times: %d’ % i)”’)
# iter times: 0
# iter times: 1
# iter times: 2
# iter times: 3
# iter times: 4


x = 10
expr = ”’
z = 30
sum = x + y + z
print(sum)
”’ # expr–expression
def func():
y = 20
exec(expr) # 60
exec(expr, {‘x’: 1, ‘y’: 2}) # 33
exec(expr, {‘x’: 1, ‘y’: 2}, {‘y’: 3, ‘z’: 4}) # 34debug分析为什么

func()


# 22filter()
”’
描述:
用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用list()来转换。
接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回TrueFalse
最后将返回True的元素放到新的列表中。
语法:
filter(function, iterable)
参数:
function–判断函数
iterable–可迭代对象
返回值:
返回一个迭代器对象
”’

# 过滤出列表中的所有奇数
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_odd(n):
return n % 2 == 1

tmplist = filter(is_odd, list1)
newlist = list(tmplist)
print(newlist)
# [1, 3, 5, 7, 9]

# 过滤出1-100中平方根是整数的数

import math

def is_sqr(x):
return math.sqrt(x) % 1 == 0

tmplist = filter(is_sqr, range(1, 101)) # 包前不包后
newlist = list(tmplist)
print(newlist)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


# 23float()
”’
描述:
用于将整数和字符串转换成浮点数
语法:
float([x])
参数:
x–整数或字符串
返回值:
返回浮点数
”’

print(float(1))
print(float(112))
print(float(123.6))
print(float(‘123’)) # 字符串


# 24str.format()
”’
描述:
Python2.6开始,新增了一种格式化字符串的函数str.format(),增强了字符串格式化功能。
基本语法是通过{} : 来代替以前的%
”’

### format函数可以接收不限个参数,位置可以不按顺序。
print(‘{} {}’.format(‘hello’, ‘world’)) # 不设置指定位置,按默认顺序
# hello world
print(‘{0} {1}’.format(‘hello’, ‘world’)) # 设置指定位置
# hello world
print(‘{2} {0} {1}’.format(‘hello’, ‘world’, ‘python’)) # 设置指定位置
# python hello world

### 也可以设置参数

print(网站名:{name},地址:{url}’.format(name=, url=‘www..com’))


# 通过字典设置参数
site = {‘name’: , ‘url’: ‘www..com’}
print(网站名:{name},地址:{url}’.format(**site)) # 拆包,需着重关注


# 通过列表索引设置参数
my_list = [, ‘www..com’]
print(网站名:{0[0]},地址:{0[1]}’.format(my_list)) # 下标用法,着重关注,“0”是必须的


### 也可以向str.format()传入对象
class AssignValue(object):
def __init__(self, value):
self.value = value

my_value = AssignValue(6)
print(‘value为:{0.value}’.format(my_value)) # 着重关注0.value用法,“0”是可选的
# value为:6

”’
format()数字格式化
^, <, > 分别是居中、左对齐、右对齐,后面带宽度
: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充
+ 表示在正数前显示+,在负数前显示
(空格)表示在正数前加空格
bodx分别是二进制、八进制、十进制、十六进制
”’

print(‘{:.2f}’.format(3.1415926)) # 保留小数点后两位3.14
print(‘{:+.2f}’.format(3.1415926)) # 带符号保留小数点后两位+3.14
print(‘{:+.2f}’.format(1)) # 带符号保留小数点后两位-1.00
print(‘{:.0f}’.format(2.71828)) # 不带小数,四舍五入3
print(‘{:0>4d}’.format(5)) # 数字补0(填充左边,宽度为40005
print(‘{:x<4d}’.format(5)) # 数字补x(填充右边,宽度为45xxx。如果输入-5会怎样? -5xx
print(‘{:,}’.format(1000000)) # 以逗号分隔的数字格式1,000,000
print(‘{:.2%}’.format(0.25)) # 百分比格式25.00%
print(‘{:.2e}’.format(1000000000)) # 指数记法1.00e+09
print(‘{:>10d}’.format(13)) # 右对齐(默认,宽度为1013
print(‘{:<10d}’.format(13)) # 左对齐(宽度为10-13
print(‘{:^10d}’.format(13)) # 中间对齐(宽度为1013
print(‘{:b}’.format(11)) # 二进制1011
print(‘{:o}’.format(11)) # 八进制13
print(‘{:d}’.format(11)) # 十进制11
print(‘{:x}’.format(11)) # 十六进制b
print(‘{:#x}’.format(11)) # 十六进制0xb
print(‘{:#X}’.format(11)) # 十六进制0XB

”’此外我们可以使用大括号{}来转义大括号,如下实例”’
print(‘{}对应的位置是{{0}}’.format(‘ ‘))
# 输出结果:runoob对应的位置是{0}

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享