python3必须掌握的内置函数(一)

python3函数

1内置函数

1、abs(numer) 返回数字的绝对值

2、all(iterable) 如果iterable所有的元素都为真值,则返回True

list = [1,2,3,2,3,3]
print(all(list))
True
list2 = [1,2,0,3,3,3]
print(all(list2))
False

3、any(iterable) 如果iterable所有的元素都为假,则返回False,否则返回True

4、ascii(object) 类似于repr,但是对非ASCII字符进行转义

print(ascii('中文'))
print(ascii('abc'))
'\u4e2d\u6587'
'abc'

5、bin(integer) 将整数类型转化为以字符串表示的二进制字面量

num = 12345
print(type(num))
strs = bin(num)
print(str)
print(type(strs))
<class 'int'>
<class 'str'>
<class 'str'>

6、bool(x) 将x转换为bool类型,并返回True或者False

7、bytearray([source,[encoding[,errors]]]) 创建一个bytearray,可以根据指定的字符串给它赋值,还可以指定编码和错误处理方式

返回一个字节数组,字节是4位二进制, [ 0 , 256 ) [0,256)

strs= "wangyincan"
print(bytearray(strs,'utf8')) #将字符串转变成字节数组
nums = 2
print(bytearray(nums)) # 传入整数,将返回一个长度为nums大小的字节数组,本例子返回一个长度为2的字节数组

bytearray(b'wangyincan')
bytearray(b'\x00\x00')

8、bytes([source,[encoding[,errors]]]) 功能和bytearray差不多,返回一个不可修改的bytes对象

strs= "wangyincan"
print(bytes(strs,'utf8')) 
nums = 2
print(bytes(nums)) 

btsA = bytearray(strs,'utf8')
btsA[1]=12  # 这里不会报错

bytesArr = bytes(strs,'utf8')
# bytesArr[1]=12 #这里会报错

b'wangyincan'
b'\x00\x00'

9、callable(object) 检查对象是否可被调用

10、chr(number) 返回指定数字的Unicode码

print(chr(1))
print(chr(41))
print(chr(122))
print(chr(112))

)
z
p

11、classmethod(func) 根据实例方法创建一个类方法 (不太明白??)

12、complex(real[,img]) 返回一个复数

cnum = complex(1,2)
print(cnum)
(1+2j)

13、delattr(object,name) 删除指定对象的指定属性的值(delete attribute) 需要注意的是,name是string

class people:
    name = ''
    sex = ''
    age = 0
    def __init__(self,name,sex,age):
        self.name = name
        self.sex = sex
        self.age = age
        

p1 = people('wang','man',12)
print(p1.name)
print(hasattr(p1,'name'))

delattr(p1,'name') # 删除属性

print(hasattr(p1,'name')) 
print(p1.name) # 发现删除的是属性的值,该属性还在
wang
True
True

14、dict([mapping-or-sequence]) 创建一个字典,可以根据另一个映射或者(key,value)列表来创建

 # 以下创建字典是等价的
 a = dict(one=1, two=2, three=3)    
 b = {'one': 1, 'two': 2, 'three': 3}
 c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
 d = dict([('two', 2), ('one', 1), ('three', 3)])
 e = dict({'three': 3, 'one': 1, 'two': 2})
 a == b == c == d == e

True

15、dir([object]) 列出当前可见作用域中的命令,或列出指定对象(大部分)的属性

import struct
dir()   # show the names in the module namespace  




['In',
 'Out',
 '_',
 '_16',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 'a',
 'b',
 'btsA',
 'bytesArr',
 'c',
 'cnum',
 'd',
 'e',
 'exit',
 'get_ipython',
 'list',
 'list2',
 'num',
 'nums',
 'p1',
 'people',
 'quit',
 'strs',
 'struct']
dir(struct)   # show the names in the struct module 


['Struct',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_clearcache',
 'calcsize',
 'error',
 'iter_unpack',
 'pack',
 'pack_into',
 'unpack',
 'unpack_from']
class Shape:
    name='w'
    def __dir__(self):
        return ['area', 'perimeter', 'location']  #从这个例子可以看出,其实dir()的输出内容首先是查看类中的__dir__函数,如果没有自定义将输出所有属性和方法的名称
s = Shape()
dir(s)
['area', 'location', 'perimeter']

16、divmod(a,b) 返回(a//b, a% b)

# 对于整数
print(divmod(5,2))

# 对于浮点数
print(divmod(5.1,2.0))
(2, 1)
(2.0, 1.0999999999999996)

17、enumerate(iterable,[start]) 迭代iterable中所有项的(index,item)。start提供开头位置

lista=['a','b','c','d']
for i in enumerate(lista):
    print(i)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

18、eval(string[,globals[,locals]]) 计算以字符串表示的表达式,还可以在指定的全局或局部作用域内进行

x = 1
y = eval('x+1')
print(y)
2

19、filter(function,sequence) 过滤器,返回一个迭代器,用function进行过滤

def isA(x):
    if x%2==0:
        return True
    else:
        return False
    
listA = [1,2,3,4,5,6,7,8,9]

for i in filter(isA,listA):
    print(i)
    
print(filter(isA,listA)) #从这一句可以发现它输出的是一个迭代器,而不是列表


2
4
6
8
<filter object at 0x00000210698CC828>

20、float(object) 将字符串或数字转化为浮点数

21、format(value[,format_spec]) 返回对指定字符串设置格式后的结果。格式设置规范与字符串方法中的format相同

format_spec的使用,后面再研究

print(format(111)) # 不加format_spec参数,效果和str(value)相同
111

22、frozenset([iterable]) 创建一个不可修改的集合,这意味着可将其添加到其他集合中去

listF = ['a','a','b',1,1,2,2,3]
fset = frozenset(listF)
print(fset)       # 从输出可以看出,它是一个集合

print(set(listF))  #set和frozenset的区别是可改变和不可改变

frozenset({1, 2, 3, 'a', 'b'})
{1, 2, 3, 'a', 'b'}

23、getattr(object,name[,default]) 返回指定对象中指定属性的值,还可以给这个属性设置默认值。如果没有指定默认值而且,该属性不存在,则返回AttributeError

24、globals() 返回一个表示当前全局作用域的字典

# globals()  

25、hasattr(object,name) 检查指定对象是否包含指定属性

26、help([object]) 调用内置的帮助系统,或打印有关指定对象的帮助信息

help(set)
Help on class set in module builtins:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |  
 |  Build an unordered collection of unique elements.
 |  
 |  Methods defined here:
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iand__(self, value, /)
 |      Return self&=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __ior__(self, value, /)
 |      Return self|=value.
 |  
 |  __isub__(self, value, /)
 |      Return self-=value.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __ixor__(self, value, /)
 |      Return self^=value.
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  add(...)
 |      Add an element to a set.
 |      
 |      This has no effect if the element is already present.
 |  
 |  clear(...)
 |      Remove all elements from this set.
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |      
 |      (i.e. all elements that are in this set but not the others.)
 |  
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |  
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |      
 |      If the element is not a member, do nothing.
 |  
 |  intersection(...)
 |      Return the intersection of two sets as a new set.
 |      
 |      (i.e. all elements that are in both sets.)
 |  
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |  
 |  issubset(...)
 |      Report whether another set contains this set.
 |  
 |  issuperset(...)
 |      Report whether this set contains another set.
 |  
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |  
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |      
 |      If the element is not a member, raise a KeyError.
 |  
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |      
 |      (i.e. all elements that are in exactly one of the sets.)
 |  
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |  
 |  union(...)
 |      Return the union of sets as a new set.
 |      
 |      (i.e. all elements that are in either set.)
 |  
 |  update(...)
 |      Update a set with the union of itself and others.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

27、hex(number) 将数字转化为16进制字符串

hex(100)
'0x64'

28、id(object) 返回指定对象独一无二的id

set1 = {1,2,3}
set2 = {1,2,3}
set3 = set1
print(id(set1))
print(id(set2))
print(id(set3))
# 可以看见set1和set3是同一个id表明它们指向同一个对象
2269512314664
2269512314216
2269512314664

29、input([prompt]) 以字符串的方式返回用户输入的数据,prompt为提升字符串

30、int(object[,radix]) 将字符串或数字转化为整数,还可以指定基数

x = int('100')
y = int('100',10)
z = int('100',16)
w = int('100',2)

print(x)
print(y)
print(z)
print(w)
100
100
256
4

31、isinstance(object,classinfo) 检查object是否是classinfo的实例,其中参数classinfo可以是类对象、类型对象、类和类型对象的元组

class dog:
    def __init__(self,name,color):
        self.name = name
        self.color = color

dog1 = dog
dog2 = dog("dd",'red')
dog3 = dog('dog3','white')
print(isinstance(dog1,dog))
print(isinstance(dog2,dog))

listdog = [dog,dog1]
tupledog = (dog,dog1)

# print(isinstance(dog2,listdog)) #这个会出错
print(isinstance(dog2,tupledog))

False
True
True

32、issubclass(class1,class2) 检查class1是否是class2的子类(每个类都被视为它自己的子类)

33、iter(object[,sentinel]) 返回一个迭代器对象,即object.iter() 。这个迭代器对象用于迭代序列(如果object支持__getitem__ )。如果指定了sentinel,这个迭代器将不断调用object,直到返回sentinel。

该方法带sentinel参数时用在文件读取到某一行停止是一个很好的例子

# with open('mydata.txt') as fp:
#     for line in iter(fp.readline,''):
#         print(line) 
# 这个例子是官方文档的,但是不知为何有问题

34、len(object) 返回指定对象的长度

35、list([sequence]) 根据指定的序列创建一个列表

lista = list((1,2,3,4))
listb = list({'a':'1','b':'2'})
listc = list({1:'a',2:'b'})
listd = list({'A',1,'B'})
print(lista)
print(listb)
print(listc)
print(listd)
[1, 2, 3, 4]
['a', 'b']
[1, 2]
[1, 'A', 'B']

36、locals() 返回一个表示当前局部作用域的字典

#locals()

37、map(function,sequence,…) 创建一个列表,用序列中的项执行function后返回的值创建

def fd(x):    
    return x//2

mapa = map(fd,[12,3,45,667])   # python2 中该函数返回list而在python3中返回map对象,是一个可迭代对象
print(type(mapa))
print(list(mapa))
<class 'map'>
[6, 1, 22, 333]

38、max(object1[,object2,…]) 如果object不是空序列,则返回其中的最大值,否则返回多个object中的最大值

maxRt1 = max([1,2,3,3,4])

maxRt2 = max([1,3],[4,6])
print(maxRt1)
print(maxRt2)
4
[4, 6]

39、nim(object1[,object2,…]) 作用同max相似

minRt1 = min([1,2,3,3,4])

minRt2 = min([1,3],[4,6])
print(minRt1)
print(minRt2)
1
[1, 3]

40、next(iterator[,default]) 返回iterator.__next()__的值,还可以指定默认值,默认值是到达了迭代器末尾时将返回的值

listq = iter([1,2,3])
print(next(listq,'end'))
print(next(listq,'end'))
print(next(listq,'end'))
print(next(listq,'end'))
print(next(listq,'end'))
1
2
3
end
end

猜你喜欢

转载自blog.csdn.net/qq_28120673/article/details/84562200
今日推荐