4.4 day14 内置函数
内置函数
1.1,作用域相关
locals :函数会以字典的类型返回当前位置的全部局部变量。
globals:函数以字典的类型返回全部全局变量。
a = 1 b = 1 print(locals()) print(globals()) # 这两个一样,因为是在全局执行的。##########################def func(argv):c = 2print(locals())print(globals()) func(3)#这两个不一样,locals() {'argv': 3, 'c': 2} #globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__': None, '__file__': 'D:/lnh.python/.../内置函数.py', 'func': <function func at 0x0000024408CF90D0>, '__name__': '__main__', '__package__': None}
1.2其他相关
1.2.1字符串类型代码的执行eval,exec,complie
eval:执行字符串类型的代码,并返回最终结果。
print(eval('4+6')) ret = eval('[1+2,3+3]') print(ret) ret = eval('{"name":"老男孩"}') print(ret,type(ret))#10 #[3, 6] #{'name': '老男孩'} <class 'dict'>
exec:执行字符串类型的代码,流程语句,执行过程,没有返回值
ret1 = ''' li = [1,2,3] for i in li:print(i) ''' exec('3 +4') exec(ret1) print(exec('3 +4')) print(exec(ret1))# 1 # 2 # 3# None# 1 # 2 # 3 # None
compile:将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。
code1 = 'for i in range(0,10): print (i)' compile1 = compile(code1,'','exec') exec (compile1)# 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9
1.2.2输入输出相关input,print
input:函数接受一个标准输入数据,返回为 string 类型。
print:打印输出。
print(333,end='') print(666,) print(111,222,333,sep='|') with open('log',encoding='utf-8',mode='a') as f1:print('5555',file=f1)# 333666 # 111|222|333 # 输入文件里
1.2.3内存相关 hash id
hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。
print(hash(12322)) print(hash('123')) print(hash('arg')) print(hash('alex')) print(hash(True)) print(hash(False)) print(hash((1,2,3)))''' 12322 -2996001552409009098 -4637515981888139739 2311495795356652852 1 0 2528502973977326415 '''
id:用于获取对象的内存地址。
print(id(123)) # 1674055952 print(id('abc')) # 2033192957072
1.2.3文件操作相关
open:函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。
1.2.4模块相关__import__
__import__:函数用于动态加载类和函数。
1.2.5帮助
help:函数用于查看函数或模块用途的详细说明。
print(help(list)) Help on class list in module builtins:class list(object)| list() -> new empty list| list(iterable) -> new list initialized from iterable's items| | Methods defined here:| | __add__(self, value, /)| Return self+value.| | __contains__(self, key, /)| Return key in self.| | __delitem__(self, key, /)| Delete self[key].| | __eq__(self, value, /)| Return self==value.| | __ge__(self, value, /)| Return self>=value.| | __getattribute__(self, name, /)| Return getattr(self, name).| | __getitem__(...)| x.__getitem__(y) <==> x[y]| | __gt__(self, value, /)| Return self>value.| | __iadd__(self, value, /)| Implement self+=value.| | __imul__(self, value, /)| Implement self*=value.| | __init__(self, /, *args, **kwargs)| Initialize self. See help(type(self)) for accurate signature.| | __iter__(self, /)| Implement iter(self).| | __le__(self, value, /)| Return self<=value.| | __len__(self, /)| Return len(self).| | __lt__(self, value, /)| Return self<value.| | __mul__(self, value, /)| Return self*value.n| | __ne__(self, value, /)| Return self!=value.| | __new__(*args, **kwargs) from builtins.type| Create and return a new object. See help(type) for accurate signature.| | __repr__(self, /)| Return repr(self).| | __reversed__(...)| L.__reversed__() -- return a reverse iterator over the list| | __rmul__(self, value, /)| Return self*value.| | __setitem__(self, key, value, /)| Set self[key] to value.| | __sizeof__(...)| L.__sizeof__() -- size of L in memory, in bytes| | append(...)| L.append(object) -> None -- append object to end| | clear(...)| L.clear() -> None -- remove all items from L| | copy(...)| L.copy() -> list -- a shallow copy of L| | count(...)| L.count(value) -> integer -- return number of occurrences of value| | extend(...)| L.extend(iterable) -> None -- extend list by appending elements from the iterable| | index(...)| L.index(value, [start, [stop]]) -> integer -- return first index of value.| Raises ValueError if the value is not present.| | insert(...)| L.insert(index, object) -- insert object before index| | pop(...)| L.pop([index]) -> item -- remove and return item at index (default last).| Raises IndexError if list is empty or index is out of range.| | remove(...)| L.remove(value) -> None -- remove first occurrence of value.| Raises ValueError if the value is not present.| | reverse(...)| L.reverse() -- reverse *IN PLACE*| | sort(...)| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*| | ----------------------------------------------------------------------| Data and other attributes defined here:| | __hash__ = NoneNoneProcess finished with exit code 0
1.2.6调用相关
callable:函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。
# print(callable(0)) # print(callable("runoob")) # def add(a,b): # return a+b # print(callable(add)) # # False # False # True
1.2.7查看内置属性
dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
dir() # 获得当前模块的属性列表 ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice'] dir([ ]) # 查看列表的方法 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
1.3迭代器生成器相关
range:函数可创建一个整数对象,一般用在 for 循环中。
next:内部实际使用了__next__方法,返回迭代器的下一个项目。
it = iter([1,2,3,4,5]) while True:try:x = next(it)print(x)except StopIteration:break# 1 # 2 # 3 # 4 # 5
iter:函数用来生成迭代器(讲一个可迭代对象,生成迭代器)。
from collections import Iterable from collections import Iterator l = [1,2,3] print(isinstance(l,Iterable)) # True print(isinstance(l,Iterator)) # Falsel1 = iter(l) print(isinstance(l1,Iterable)) # True print(isinstance(l1,Iterator)) # True
1.4基础数据类型相关
1.4.1数字相关
数据类型:
bool:用于将给定参数转换为布尔类型,如果没有参数,返回False。
int:函数用于将一个字符串或数字转换为整型。
print(int()) # 0 print(int('12')) # 12 print(int(3.6)) # 3 print(int('0100',base=2)) # 将2进制的 0100 转化成十进制。结果为 4
float:函数用于将整数和字符串转换成浮点数。
complex:函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
>>>complex(1, 2) (1 + 2j)>>> complex(1) # 数字 (1 + 0j)>>> complex("1") # 当做字符串处理 (1 + 0j)# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错 >>> complex("1+2j") (1 + 2j)
进制转换:
bin:将十进制转换成二进制并返回。
oct:将十进制转化成八进制字符串并返回。
hex:将十进制转化成十六进制字符串并返回。
print(bin(10),type(bin(10))) # 0b1010 <class 'str'> print(oct(10),type(oct(10))) # 0o12 <class 'str'> print(hex(10),type(hex(10))) # 0xa <class 'str'>
数字运算:
abs:函数返回数字的绝对值。
divmod:计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)。
round:保留浮点数的小数位数,默认保留整数。
pow:求x**y次幂。(三个参数为x**y的结果对z取余)
print(abs(-5)) print(divmod(4,2)) print(divmod(7,2)) print(round(7/3,3)) print(round(7/3,2)) print(round(3.42345,3)) print(pow(2,3)) print(pow(2,3,3)) print(pow(2,4,3))# 5 # (2, 0) # (3, 1) # 2.333 # 2.33 # 3.423 # 8 # 2 # 1
sum:对可迭代对象进行求和计算(可设置初始值)。
min:返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)。
max:返回可迭代对象的最大值(可加key,key为函数名,通过函数的规则,返回最大值)。
print(sum([1,2,3])) print(sum([1,2,3],100)) print(min([1,2,3])) ret = min([1,2,-5],key=abs) print(ret) dic = {'a':3,'b':2,'c':1} print(min(dic,key=lambda x:dic[x])) print(max([1,2,3])) ret = max([1,2,-5,],key=abs) print(ret) dic = {'a':3,'b':2,'c':1} print(max(dic,key=lambda x:dic[x]))# 6 # 106 # 1 # 1 # c # 3 # -5 # a
1.4.2和数据结构相关
列表和元祖
list:将一个可迭代对象转化成列表(如果是字典,默认将key作为列表的元素)。
tuple:将一个可迭代对象转化成元祖(如果是字典,默认将key作为元祖的元素)。
l = list((1,2,3)) print(l) l = list({1,2,3}) print(l) l = list({'k1':1,'k2':2}) print(l) tu = tuple((1,2,3)) print(tu) tu = tuple([1,2,3]) print(tu) tu = tuple({'k1':1,'k2':2}) print(tu)# [1, 2, 3] # [1, 2, 3] # ['k2', 'k1'] # (1, 2, 3) # (1, 2, 3) # ('k2', 'k1')
相关内置函数
reversed:将一个序列翻转,并返回此翻转序列的迭代器。
slice:构造一个切片对象,用于列表的切片。
ite = reversed(['a',2,3,'c',4,2]) for i in ite:print(i)li = ['a','b','c','d','e','f','g'] sli_obj = slice(3) print(li[sli_obj])sli_obj = slice(0,7,2) print(li[sli_obj])ite = reversed(['a',2,3,'c',4,2]) for i in ite:print(i)li = ['a','b','c','d','e','f','g'] sli_obj = slice(3) print(li[sli_obj])sli_obj = slice(0,7,2) print(li[sli_obj])# 2 # 4 # c # 3 # 2 # a # ['a', 'b', 'c'] # ['a', 'c', 'e', 'g']
字符串相关
str:将数据转化成字符串。
format:与具体数据相关,用于计算各种小数,精算等。
#字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐 print(format('test', '<20')) print(format('test', '>20')) print(format('test', '^20'))#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None >>> format(3,'b') #转换成二进制 '11' >>> format(97,'c') #转换unicode成字符 'a' >>> format(11,'d') #转换成10进制 '11' >>> format(11,'o') #转换成8进制 '13' >>> format(11,'x') #转换成16进制 小写字母表示 'b' >>> format(11,'X') #转换成16进制 大写字母表示 'B' >>> format(11,'n') #和d一样 '11' >>> format(11) #默认和d一样 '11'#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None >>> format(314159267,'e') #科学计数法,默认保留6位小数 '3.141593e+08' >>> format(314159267,'0.2e') #科学计数法,指定保留2位小数 '3.14e+08' >>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示 '3.14E+08' >>> format(314159267,'f') #小数点计数法,默认保留6位小数 '314159267.000000' >>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数 '3.141593' >>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数 '3.14159267' >>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数 '3.1415926700' >>> format(3.14e+1000000,'F') #小数点计数法,无穷大转换成大小字母 'INF'#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数 >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点 '3e-05' >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点 '3.1e-05' >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点 '3.14e-05' >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写 '3.14E-05' >>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点 '3' >>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点 '3.1' >>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点 '3.14' >>> format(0.00003141566,'.1n') #和g相同 '3e-05' >>> format(0.00003141566,'.3n') #和g相同 '3.14e-05' >>> format(0.00003141566) #和g相同 '3.141566e-05'
bytes:用于不同编码之间的转化。
s = '你好' bs = s.encode('utf-8') print(bs) s1 = bs.decode('utf-8') print(s1) bs = bytes(s,encoding='utf-8') print(bs) b = '你好'.encode('gbk') b1 = b.decode('gbk') print(b1.encode('utf-8'))# b'\xe4\xbd\xa0\xe5\xa5\xbd' # 你好 # b'\xe4\xbd\xa0\xe5\xa5\xbd' # b'\xe4\xbd\xa0\xe5\xa5\xbd'
bytearry:返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
ret = bytearray('alex',encoding='utf-8') print(id(ret)) print(ret) print(ret[0]) ret[0] = 65 print(ret) print(id(ret))# 2578886113632 # bytearray(b'alex') # 97 # bytearray(b'Alex') # 2578886113632
memoryview
ret = memoryview(bytes('你好',encoding='utf-8')) print(len(ret)) print(ret) print(bytes(ret[:3]).decode('utf-8')) print(bytes(ret[3:]).decode('utf-8'))# 6 # <memory at 0x000001EFE4647A08> # 你 # 好
ord:输入字符找该字符编码的位置
chr:输入位置数字找出其对应的字符
ascii:是ascii码中的返回该值,不是就返回/u...
# ord 输入字符找该字符编码的位置 # print(ord('a')) # print(ord('中'))# chr 输入位置数字找出其对应的字符 # print(chr(97)) # print(chr(20013))# 是ascii码中的返回该值,不是就返回/u... # print(ascii('a')) # print(ascii('中'))
repr:返回一个对象的string形式(原形毕露)。
# %r 原封不动的写出来 # name = 'taibai' # print('我叫%r'%name)# repr 原形毕露 print(repr('{"name":"alex"}')) print('{"name":"alex"}')# '{"name":"alex"}' # {"name":"alex"}
数据集合
dict:创建一个字典。
set:创建一个集合。
frozenset:返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
相关内置函数
len:返回一个对象中元素的个数。
sorted:对所有可迭代的对象进行排序操作。
L = [('a', 1), ('c', 3), ('d', 4), ('b', 2), ] sorted(L, key=lambda x: x[1]) # 利用key print(sorted(L)) # [('a', 1), ('b', 2), ('c', 3), ('d', 4)]students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] sorted(students, key=lambda s: s[2]) # 按年龄排序 print(sorted(students)) # [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]sorted(students, key=lambda s: s[2], reverse=True) # 按降序 print(sorted(students)) # [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
enumerate:枚举,返回一个枚举对象。
print(enumerate([1,2,3])) for i in enumerate([1,2,3]):print(i) for i in enumerate([1,2,3],100):print(i)# <enumerate object at 0x0000027D32A21480> # (0, 1) # (1, 2) # (2, 3) # (100, 1) # (101, 2) # (102, 3)
all:可迭代对象中,全都是True才是True
any:可迭代对象中,有一个True 就是True
print(all([1,2,True,0])) print(any([1,'',0]))# False # True
zip:函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。
l1 = [1,2,3,] l2 = ['a','b','c',5] l3 = ('*','**',(1,2,3)) for i in zip(l1,l2,l3):print(i)# (1, 'a', '*') # (2, 'b', '**') # (3, 'c', (1, 2, 3))
filter:过滤·。
def func(x):return x%2 == 0 ret = filter(func,[1,2,3,4,5,6,7]) print(ret) for i in ret:print(i)# <filter object at 0x0000016FD4F439B0> # 2 # 4 # 6
map:会根据提供的函数对指定序列做映射。
>>>def square(x) : # 计算平方数 ... return x ** 2 ... >>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方 [1, 4, 9, 16, 25] >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数 [1, 4, 9, 16, 25]# 提供了两个列表,对相同位置的列表数据进行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19]
匿名函数
匿名函数:为了解决那些功能很简单的需求而设计的一句话函数。
def calc(n):return n*n print(calc(10))cal = lambda n:n*n print(cal(10))#100 #100
上面是我们对calc这个匿名函数的分析,下面给出了一个关于匿名函数格式的说明
函数名 = lambda 参数 :返回值#参数可以有多个,用逗号隔开 #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值 #返回值和正常的函数一样可以是任意数据类型
我们可以看出,匿名函数并不是真的不能有名字。
匿名函数的调用和正常的调用也没有什么分别。 就是 函数名(参数) 就可以了~~~
匿名函数与内置函数举例:
l=[3,2,100,999,213,1111,31121,333] print(max(l))dic={'k1':10,'k2':100,'k3':30} print(max(dic)) print(dic[max(dic,key=lambda k:dic[k])])# 31121 # k3 # 100
res = map(lambda x:x**2,[1,5,7,4,8]) for i in res:print(i)# 1 # 25 # 49 # 16 # 64
res = filter(lambda x:x>10,[5,8,11,9,15]) for i in res:print(i)# 11 # 15
转载于:https://www.cnblogs.com/kateli/p/8734337.html
4.4 day14 内置函数相关推荐
- day14——内置函数
** globals() 已字典的形式返回全局变量 ** locals() 已字典的形式返回当前位置的局部变量 q = 666 def wrapper(argv): a = 3 print(l ...
- 第三周 day14:内置函数
⼀. 本节主要内容: 1. 内置函数 什么是内置函数? 就是python给你提供的. 拿来直接⽤的函数, 比如print., input等等. 截⽌ 到python版本3.6.2 python⼀共提供 ...
- format函数python生成列表_python 全栈开发,Day14(列表推导式,生成器表达式,内置函数)...
一.列表生成式 生成1-100的列表 li = [] for i in range(1,101): li.append(i) print(li) 执行输出: [1,2,3...] 生成python1期 ...
- day11 - 15(装饰器、生成器、迭代器、内置函数、推导式)
day11:装饰器(装饰器形成.装饰器作用.@语法糖.原则.固定模式) 装饰器形成:最简单的.有返回值的.有一个参数的.万能参数 函数起的作用:装饰器用于在已经完成的函数前后增加功能 语法糖:使代码变 ...
- Python 常用内置函数map、zip、filter、reduce、enumerate
Python 中有许多非常实用的内置函数,通过这些函数我们可以方便的实现某些功能,下面就列举一些常用的内置函数. 1. map() 函数 map() 可以根据提供的函数对指定序列做映射,它接受一个函数 ...
- 2021年大数据Hive(五):Hive的内置函数(数学、字符串、日期、条件、转换、行转列)
全网最详细的Hive文章系列,强烈建议收藏加关注! 后面更新文章都会列出历史文章目录,帮助大家回顾知识重点. 目录 系列历史文章 前言 Hive的内置函数 一.数学函数 1. 取整函数: round ...
- python3 内置函数map 返回的迭代器转为列表
python3 内置函数map 返回的是迭代器,python2 返回的才是列表, 在python3中想要使用需要把迭代器在转换成列表 list_a = [1, 2, 3, 4, 5]def add(n ...
- Python Day26:多态、封装、内置函数:__str__、__del__、反射(反省)、动态导入模块...
## 多态 ```python OOP中标准解释:多个不同类型对象,可以响应同一个方法,并产生不同结果,即为多态 多态好处:只要知道基类使用方法即可,不需要关心具体哪一个类的对象实现的,以不变应万变, ...
- 13装饰器和内置函数
装饰器 # 1.装饰用的工具# import time #内置函数计算函数运行时间 # print(time.time())# import time # def func(): # start_ti ...
最新文章
- java7特性_Java7特性中,abstract class和interf
- GAN是一种特殊的损失函数?
- python是多模型语言_Django多语言post模型
- engineering department induction ppt
- 图片轮播,纯js+css
- yum -y install与yum install有什么不同
- 解决:Gitlab上出现“You won‘t be able to pull or push project code via SSH until you add an SSH key to you
- 程序员的职业选择,你应该知道的,持续更新ing
- 基于Java毕业设计优课网设计与实现源码+系统+mysql+lw文档+部署软件
- Java编译器IDE-文本编辑器
- 关于AD9371FilterWizard无法运行问题
- 室友哪些不该看的东西被你无意之间看到了?
- 浏览器全面禁止第三方Cookie
- Dynamics 365 IFD设置反向代理后无法跳转登录页的解决方法
- VS2017无法打开graphics.h解决方法
- Python免费下载哔哩哔哩视频,只需一行代码!
- ShardingJDBC使用总结
- 几个有关智能的小问题
- 植物叶片相对电导率的测定
- 360安全卫士,还有这么多,小兄弟?