Python 学习笔记 (十四) python3内置函数(53-68)
【摘要】 史上最为详细的python学习笔记,记录学习过程的知识点和难点
# 53、range():
'''
描述:
Python3 range()函数返回的是一个可迭代对象(类型是对象),而不是列表类型,所以打印的时候不会打印列表,而是range(0, 10)。
Python3 list()函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表。
Python2 range()函数返回的是列表。https://www.runoob.com/python/python-func-range.html
语法:
range(stop)
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)
返回值:
'''
print(range(10)) # range(0, 10)
print(type(range(10))) # <class 'range'>,可迭代对象
print(list('10')) # ['1', '0']
print(type(list('10'))) # <class 'list'>,对象迭代器
print(list(range(10))) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(list(range(10)))) # <class 'list'>
print(range(5)) # range(0, 5)
for i in range(5):
print(i, end=',') # 0,1,2,3,4,
print()
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(1, 0))) # []
# 54、repr():
'''
描述:
将对象转化为供解释器读取的形式
语法:
repr(object)
参数:
object--对象
返回值:
返回一个对象的string格式
'''
s = 'Runoob'
print(repr(s)) # 'Runoob'
print(s) # Runoob
dict1 = {'runoob': 'runoob.com', 'google': 'google.com'}
print(repr(dict1)) # {'runoob': 'runoob.com', 'google': 'google.com'}
print(dict1) # {'runoob': 'runoob.com', 'google': 'google.com'}
# 55、reversed():
'''
描述:
reversed()函数返回一个反转的迭代器reverseiterator
语法:
reversed(seq)
参数:
seq--要转换的序列,可以是string, list, tuple或range
返回值:
返回一个反转的迭代器reverseiterator
'''
# 字符串
seq_string = 'runoob'
print(reversed(seq_string))
# <reversed object at 0x0000028DB90DB130>
print(list(reversed(seq_string)))
# ['b', 'o', 'o', 'n', 'u', 'r']
# 列表
seq_list = [1, 2, 4, 3, 5]
print(reversed(seq_list))
# <list_reverseiterator object at 0x000001F3333AB0A0>
print(list(reversed(seq_list))) # [5, 3, 4, 2, 1]
# 元组
seq_tuple = ('b', 'o', 'o', 'n', 'u', 'r')
print(reversed(seq_tuple))
# <reversed object at 0x000002E6B0C1B0A0>
print(list(reversed(seq_tuple))) # ['r', 'u', 'n', 'o', 'o', 'b']
# range
seq_range = range(5, 9)
print(reversed(seq_range))
# <range_iterator object at 0x0000025D50909CF0>
print(list(reversed(seq_range))) # [8, 7, 6, 5]
# 56、round():
'''
描述:
返回浮点数x的四舍五入值,准确地说保留值将保留到离上一位更近的一端(四舍六入)
提示:精度要求高的,不建议使用该函数
语法:
round(x[, n])
参数:
x--数字表达式
n--表示小数点位数,其中x需要四舍五入,默认值为0
返回值:
返回浮点数x的四舍五入值
'''
print('round(70.23456):', round(70.23456))
# round(70.23456): 70
print('round(56.659, 1):', round(56.659, 1)) # 五入
# round(56.659, 1): 56.7
print('round(80.264, 2):', round(80.264, 2)) # 四舍
# round(80.264, 2): 80.26
print('round(100.000456, 3):', round(100.000456, 3)) # 四舍
# round(100.000056, 3): 100.0
print('round(-100.000456, 3):', round(-100.000456, 4)) # 五入
# round(-100.000056, 3): -100.0
# 看一下给的例子
print(round(2.675, 2))
'''
按我们的想法返回结果应该是2.68,可结果却是2.67,为什么?
这跟浮点数的精度有关。
我们知道在机器中浮点数不一定能精确表达,因为换算成一串1和0后可能是无线位数的,机器已经做出了截断处理。
那么在机器中保存的2.675这个数字就比实际数字要小那么一点点。
这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。
'''
# 57、set():
'''
描述:
创建一个无序、不重复的元素集,可进行关系测试、删除重复数据,还可以计算交集、差集、并集等。
语法:
set([iterable])
参数:
iterable--可迭代对象
返回值:
返回新的集合对象
'''
x = set('runoob')
y = set('google')
print(x, y) # 无序、不重复的集合{},重复的会被删除
# {'u', 'r', 'o', 'b', 'n'} {'g', 'o', 'e', 'l'}
print(x & y) # 交集 {'o'}
print(x | y) # 并集 {'g', 'u', 'n', 'e', 'b', 'l', 'o', 'r'}
print(x - y) # 差集 {'r', 'u', 'b', 'n'}
# 58、setattr():
'''
描述:
setattr()函数对应的函数是getattr(),用于设置属性值,该属性不一定是存在的。
语法:
setattr(object, name, value)
参数:
object--对象
name--字符串、对象属性
value--属性值
返回值:
无
'''
class A(object):
bar = 1
a = A()
print(getattr(a, 'bar')) # 获取属性bar值 1
setattr(a, 'bar', 5) # 设置属性bar值
print(a.bar) # 打印属性值 5
# 如果属性不存在会创建一个新的对象属性,并对属性赋值
class A():
name = 'runoob'
a = A()
print(getattr(a, 'name')) # 获取属性name值 runoob
setattr(a, 'age', 23) # 创建并设置属性age值,
print(a.age) # 23
# 59、slice():
'''
描述:
slice()函数实现切片对象,主要用在切片操作函数里的参数传递
语法:
slice(stop)
slice(start, stop[, step])
参数:
start--起始位置
stop--结束位置
step--间距
返回值:
返回一个切片对象
'''
# 设置截取5个元素的切片
myslice = slice(5)
print(myslice) # slice(None, 5, None)
arr = range(10) # range()函数返回一个可迭代对象
print(arr)
# range(0, 10)
print(list(arr)) # list()函数是对象迭代器
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 截取5个元素 range(0, 5)
print(arr[myslice])
print(list(arr[myslice])) # [0, 1, 2, 3, 4],
print(list(arr[slice(5)])) # [0, 1, 2, 3, 4]
'''
# range()函数返回一个可迭代对象(类型是对象,不是列表,所以不会打印列表)
# list()函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表
'''
# 60、sorted():
'''
描述:
对所有可迭代的对象进行排序操作
sort()与sorted()的区别:
sort是应用在list上的方法,sorted可以对所有可迭代的对象进行排序操作。
list的sort方法返回的是对已经存在的列表进行操作,
内建函数sorted方法返回的是一个新的list,而不是在原来的基础上进行的操作。
总结一句话:sort对原list进行排序,sorted排序后返回一个新的list。
语法:
sorted(iterable, key=None, reverse=False)
参数:
iterable--可迭代对象
key--主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自可迭代对象中,
指定可迭代对象中的一个元素来进行排序。
reverse--排序规则,reverse=True为降序,reverse=False为升序(默认)
返回值:
返回一个重新排序的列表list
'''
list1 = [5, 2, 3, 1, 4]
print(list1) # [5, 2, 3, 1, 4]
print(sorted(list1)) # 默认为升序 [1, 2, 3, 4, 5]
print(list1) # [5, 2, 3, 1, 4],原始list没有被修改
'''
你也可以使用list的sort()方法,这个方法会修改原始的list(返回值为None)通常这个方法不如sorted()方便,
如果你不需要原始的list,list.sort()方法效率会稍微高一些
'''
list2 = [5, 2, 3, 1, 4]
print(list2) # [5, 2, 3, 1, 4]
print(list2.sort()) # sort()的返回值为None
print(list(list2)) # [1, 2, 3, 4, 5]
print(list2) # [1, 2, 3, 4, 5],原始list被修改
'''
另一个区别在于list.sort()方法只为list定义,
而sorted()函数可以接收任何类型的iterable
'''
dict1 = {1: 'D', 4: 'B', 3: 'B', 5: 'C', 2: 'A'}
# 对字典使用sorted()
print(sorted(dict1)) # [1, 2, 3, 4, 5]
# 原始字典没有被修改
print(dict1) # {1: 'D', 4: 'B', 3: 'B', 5: 'C', 2: 'A'}
# 利用key进行倒序排序 key=lambda x: x *-1
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list, key=lambda x: x *-1) # 这里的*-是什么意思?降序排序
result_list2 = sorted(example_list, key=lambda x: x *+1) # 升序排序
print(result_list) # [7, 6, 5, 4, 3, 2, 1, 0]
print(result_list2) # [0, 1, 2, 3, 4, 5, 6, 7]
# 要进行反向排序,传入第三个参数reverse=True
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
print(sorted(example_list, reverse=True)) # [7, 6, 5, 4, 3, 2, 1, 0] 降序
print(example_list) # [5, 0, 6, 1, 2, 7, 3, 4]
print(list(reversed(sorted(example_list)))) # [7, 6, 5, 4, 3, 2, 1, 0] 降序
print('================')
''' sorted应用1:通过key的值来进行数组/字典的排序 '''
array = [{'age': 20, 'name': 'alice'}, {'age': 25, 'name': 'bruce'}, {'age': 10, 'name': 'carl'}]
array = sorted(array, key=lambda x: x['age']) # 按key排序
print(array)
# [{'age': 10, 'name': 'carl'}, {'age': 20, 'name': 'alice'}, {'age': 25, 'name': 'bruce'}]
array2 = sorted(array, key=lambda x: x['name'])
print(array2)
# [{'age': 20, 'name': 'alice'}, {'age': 25, 'name': 'bruce'}, {'age': 10, 'name': 'carl'}]
''' sorted应用2 多列排序:先按照成绩降序排序,相同成绩的按照名字升序排序 '''
dict1 = [{'name': 'alice', 'score': 38}, {'name': 'bob', 'score': 18},
{'name': 'darl', 'score': 28}, {'name': 'christ', 'score': 28}]
result = sorted(dict1, key=lambda x: (-x['score'], x['name'])) # 注意此处-号降序的用法
print(result)
# [{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, {'name': 'bob', 'score': 18}]
# 61、staticmethod():
'''
描述:
python staticmethod返回函数的静态方法。
该方法不强制要求传递参数,如下声明一个静态方法:
class C(object):
@staticmethod
def func(arg1, arg2, ...):
...
以上实例声明了静态方法func,从而可以实现实例化使用c().func(),
当然也可以不实例化调用该方法.func()。
函数语法:
staticmethod(function)
参数:
无
返回值:
无
'''
class C(object):
@staticmethod
def func():
print('runoob')
C.func() # 静态方法无需实例化,runoob
cobj = C()
cobj.func() # 也可以实例化后调用,runoob
# 62、str():
'''
描述:
str()函数将对象转化为适于人阅读的形式
语法:
str(object='')
参数:
object--对象
返回值:
返回一个对象的string格式
'''
s = 'runoob'
print(str(s)) # runoob
dict1 = {'runoob': 'runoob.com', 'google': 'google.com'}
print(str(dict1)) # {'runoob': 'runoob.com', 'google': 'google.com'}
# 63、sum():
'''
描述:
sum()方法对序列进行求和计算。
语法:
sum(iterable[, start])
参数:
iterable--可迭代对象,如列表、元组、集合
start--指定相加的参数,如果没有设置这个值,默认为0
返回值:
返回计算结果
'''
print(sum([0, 1, 2])) # 列表计算总和 3
print(sum((2, 3, 4), 1)) # 元组计算总和后再加1 10
print(sum([0, 1, 2, 3, 4], 2)) # 列表计算总和后再加2 12
# 64、super():
'''
描述:
super()函数是用于调用父类(超类)的一个方法。
super()用来解决多重继承问题,在使用 单继承 时 直接用类名调用父类方法 没有问题,
然是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO(Method Resolution Order)是类的方法解析顺序表,其实也就是继承父类方法时的顺序表。
语法:
super(type[, object-or-type])
参数:
type--类
object-or-type--类,一般是self
Python3.x和Python2.x的一个区别是:
Python3可以直接使用super().xxx代替super(class, self).xxx
返回值:
无
'''
### Python3.x实例
class A: # Python3.x默认继承自object
def add(self, x):
y = x + 1
print(y)
class B(A):
def add(self, x):
super().add(x) # 注意此处用法
b = B()
b.add(12) # 13
### Python2.x实例
class A(object): # Python2.x需手动继承object
def add(self, x):
y = x + 1
print(y)
class B(A):
def add(self, x):
super(B, self).add(x) # 在Python3.x中会提示:'B' is not an instance or a subclass of 'B'
b = B()
b.add(15) # 16
### 以下展示了使用super()函数的实例
class FooParent(object): # 可省略object
def __init__(self):
self.parent = 'I\'m the parent.'
print('parent')
def bar(self, message):
print('%s from Parent' % message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild, self)首先找到FooChild的父类(也就是类FooParent),
# 然后把类FooChild的对象转换为类FooParent的对象。
super(FooChild, self).__init__()
print('child')
def bar(self, message):
super(FooChild, self).bar(message)
print('FooChild().bar.message: ', message)
print('child bar function')
print(self.parent)
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
'''
运行结果:
parent
child
HelloWorld from Parent
child bar function
I'm the parent.
'''
# 65、tuple():
'''
描述:
tuple()函数将可迭代系列(如字符串、列表、字典、集合)转换为元组。
语法:
tuple(iterable)
参数:
iterable--要转换为元组的可迭代序列。
返回值:
返回元组。
'''
# 将字符串转换为元组
str1 = 'hello world'
print(str1) # hello world
print(tuple(str1)) # ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
# 将列表转换为元组
list1 = ['Google', 'Taobao', 'Runoob', 'Baidu']
print(list1) # ['Google', 'Taobao', 'Runoob', 'Baidu']
print(tuple(list1)) # ('Google', 'Taobao', 'Runoob', 'Baidu')
# 将字典转换为元组
dict1 = {'www': 123, 'aaa': 456, 'nnn': 789}
print(dict1) # {'www': 123, 'aaa': 456, 'nnn': 789}
print(tuple(dict1)) # 将字典转为元组时,只保留key,如('www', 'aaa', 'nnn')
# 将集合转换为元组
set1 = {'c', 'd', 'b', 'a'}
print(set1) # {'c', 'a', 'd', 'b'}
print(tuple(set1)) # ('c', 'a', 'd', 'b')
# 66、type():
'''
描述:
type()函数如果只有第一个参数则返回对象的类型,如果有三个参数则返回新的类型对象。
isinstance()与type()的区别:
isinstance()会认为子类是一种父类类型,考虑继承关系。
type()不会认为子类是一种父类类型,不考虑继承关系。
语法:
type(object)
type(name, bases, dict)
参数:
name--类的名称
bases--基类的元组
dict--字典,类内定义的命名空间变量。
返回值:
一个参数返回对象类型,三个参数则返回新的类型对象。
'''
### 一个参数实例
print(type(1)) # <class 'int'>
print(type('runoob')) # <class 'str'>
print(type([2])) # <class 'list'>
print(type({0: 'zero'})) # <class 'dict'>
x = 1
print(type(x) == int) # 判断类型是否相等,True
### 三个参数实例
class X(object):
a = 1
# 产生一个新的类型X
x = type('X', (object,), dict(a = 1))
print(x) # <class '__main__.X'>
### type()与isinstance()区别:
class A:
pass
class B(A):
pass
print(isinstance(A(), A)) # True
print(type(A()) == A) # True
print(isinstance(B(), A)) # 考虑继承关系,True
print(type(B()) == A) # 不考虑继承关系,False
# 67、vars():
'''
描述:
vars()函数返回对象object的属性和属性值的字典对象
语法:
vars([object])
参数:
object--对象
返回值:
返回对象object的属性和属性值的对象,
如果没有参数,就打印当前调用位置的属性和属性值,类似locals()。
'''
print(vars())
# {'__name__': '__main__', '__doc__': '\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000014F9DD80910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Project/Pycharm/Project1/review1.py', '__cached__': None, 'C': <class '__main__.C'>, 'cobj': <__main__.C object at 0x0000014F9F9D89D0>, 's': 'runoob', 'dict1': {'www': 123, 'aaa': 456, 'nnn': 789}, 'A': <class '__main__.A'>, 'B': <class '__main__.B'>, 'b': <__main__.B object at 0x0000014F9F9EB850>, 'FooParent': <class '__main__.FooParent'>, 'FooChild': <class '__main__.FooChild'>, 'fooChild': <__main__.FooChild object at 0x0000014F9F9EB940>, 'str1': 'hello world', 'list1': ['Google', 'Taobao', 'Runoob', 'Baidu'], 'set1': {'c', 'd', 'a', 'b'}, 'x': <class '__main__.X'>, 'X': <class '__main__.X'>}
class Runoob:
a = 1
print(vars(Runoob))
# {'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Runoob' objects>, '__weakref__': <attribute '__weakref__' of 'Runoob' objects>, '__doc__': None}
runoob = Runoob()
print(vars(runoob)) # 注意此处没有继承类Runoob的属性a
# {}
# 对于x = 1这样的一个赋值语句,语句执行后名称x引用到值1.就像字典一样,键引用值,
# 当然,变量和所对应的值用的是个“不可见”的字典,我们可以使用vars函数来返回这个字典。
x = 1
scope = vars()
print(scope)
# {'__name__': '__main__', '__doc__': '\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001EC46D30910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Project/Pycharm/Project1/review1.py', '__cached__': None, 'C': <class '__main__.C'>, 'cobj': <__main__.C object at 0x000001EC489689D0>, 's': 'runoob', 'dict1': {'www': 123, 'aaa': 456, 'nnn': 789}, 'A': <class '__main__.A'>, 'B': <class '__main__.B'>, 'b': <__main__.B object at 0x000001EC4897B880>, 'FooParent': <class '__main__.FooParent'>, 'FooChild': <class '__main__.FooChild'>, 'fooChild': <__main__.FooChild object at 0x000001EC4897B970>, 'str1': 'hello world', 'list1': ['Google', 'Taobao', 'Runoob', 'Baidu'], 'set1': {'a', 'd', 'c', 'b'}, 'x': 1, 'X': <class '__main__.X'>, 'Runoob': <class '__main__.Runoob'>, 'runoob': <__main__.Runoob object at 0x000001EC4897BB20>, 'scope': {...}}
print(scope['x'])
# 1
# 68、__import__():
'''
描述:
__import__()函数用于动态加载类和函数。
如果一个模块经常变化就可以使用__import__()来动态加载
语法:
__import__(name[, globals[, locals[, fromlist[, level]]]])
参数:
name--模块名
返回值:
返回元组列表
'''
__import__('xxx.py')
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)