Python之路—Day10

内置函数


 all: 所有iterable类型,包含的元素要全为真才返回真

>>> all([0,-1,5])
False
>>> all([-1,5])
True

any:有iterable类型,非空且包含任一为真element就返回true

>>> any([])
False
>>> any([0])
False
>>> any([0,12])
True

ascii:

>>> a = ascii([1,2,"中文"])   
>>> print(type(a),[a])
<class 'str'> ["[1, 2, '\\u4e2d\\u6587']"]
>>> #把内存的数据转换为可打印的字符串格式

bin:

>>> bin(2)  #把十进制转换为二进制
'0b10'
>>> #convert an integer number to a binary string ,需要整数才能转

bool:判断真假

>>> bool([])     
False
>>> bool(0)     
False
>>> bool([0,1])
True

bytes:转换为二进制格式

>>> a = bytes("abcde",encoding='utf-8')
>>> print(a.capitalize(),a)
b'Abcde' b'abcde'
>>> a[0]
97
>>> a[0] = 100    #当想修改它时会报错
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a[0] = 100
TypeError: 'bytes' object does not support item assignment
>>> 

bytearray:

>>> b = bytearray("abcde",encoding='utf-8')
>>> b[0]
97
>>> b[0] = 102
>>> print(b)
bytearray(b'fbcde')
>>> #bytearray变成变成二进制列表的形式,并可以修改,很少用到

callable:

>>> print(callable([]))
False
>>> #判断是否可以调用,后面能加括号的就是能调用的,比如函数
>>> def sayhi():
    pass
>>> callable(sayhi())  #此时为函数运行结果,不能调用
False
>>> callable(sayhi) #注意此时函数为内存地址,可以调用
True

chr:

>>> chr(87) #把ASCII中的数字对应的元素返回出来
'W'

ord:

>> ord('a') #把元素返回为ascii中对应的数字号码
97

compile:#compile(str,'err.log','exec or eval') 把字符串编译为可运行的代码

>>> code = 'for i in range(2):print(i)'
>>> compile(code,'','exec')
<code object <module> at 0x000001C8899C89C0, file "", line 1>
>>> exec(code)  #相当于import了这个模块,然后执行
>>>>
0
1
2

dict:

>>> {}
{}
>>> dict()  #定义一个字典
{}

dir:

>>> a = {}
>>> dir(a)  #查可用方法
['__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__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> 

divmod:

divmod(5,2)  # 5除以2 并返回商和余数
(2, 1)

lambda: 匿名函数

>>> x = lambda n:3 if n<3 else n
>>> x(7)
7

猜你喜欢

转载自www.cnblogs.com/gkx0731/p/9463638.html