一:内置类型:
1,class int(object):
"""
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int(‘0b100‘, base=0)
4
它使用C中的long实现,拥有准确的精度,此外布尔类型是整数的子类型
"""
2,class float(object):
"""
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
浮点数使用C中的double实现,Python放弃了单精度浮点型,float总是不精确的,所以不要用于金钱
"""
3,class bool(int):
"""
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
"""
4,class enumerate(object):
"""
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
for example:
l =[5,9,8,4,5,6,2,1]
for index ,val in enumerate(l):
print(index,val)
"""
5,class complex(object):
"""
complex(real[, imag]) -> complex number
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.
复数由实数与虚数构成,是数的概念扩展,在数值的后面加 ‘J‘ 或 ‘j‘ 进行定义,不常用
"""
二:内置函数:
1), 重要的三个:map() ,reduce() ,filter()
#=================================================
#=====================map=========================
#=================================================
#map() 对每个元素都计算
#内置函数map () 我们先看下面的程序
# def func(arr):
# ret = []
# for i in arr:
# ret.append(i**2)
# return ret
#
# ret = func([1,2,3,5,4,7])
# print(ret)
#此时如果突然想改变逻辑,i + 1 然后再添加到ret 中,只能重新写了,这样不好
#==========================================
# def abstract_func(func,arr):
# ret = []
# for i in arr:
# ret.append(func(i)) #将i 进行相应的运算之后加到ret
# return ret
#
# def square(i):
# return i**2
#
# l = [1,4,6,5,4,2,3,5]
# ret = abstract_func(square,l)
# print(ret)
# #此时如果想换逻辑运算,比如加1
# def add_one(i):
# return i+1
# ret = abstract_func(add_one,l)
# print(ret)
#============================================
#第二个方案已经很好了,但是我们知道匿名函数,所以我们用匿名函数取代里面的计算逻辑
l = [1,4,6,5,4,2,3,5]
def abstract_func(func,arr):
ret = []
for i in arr:
ret.append(func(i))
return ret
ret = abstract_func(lambda x:x**2,l)
# print(ret)
ret = abstract_func(lambda x:x+1,l)
# print(ret)
#这就更加完美了,perfect !
#=================================================
#内置函数 map()
ret = map(lambda x:x+1,l) #当然第一个参数,传的不是匿名函数也是可以的, 第二个参数是可迭代对象
# print(ret) #map 的内部会做循环的。 <map object at 0x0000021911F5B2E8>
# print(list(ret)) #将map 对象变为列表 [2, 5, 7, 6, 5, 3, 4, 6]
#=================================================
#=====================filter======================
#=================================================
#过滤出指定的元素
#另一个内置函数filter()
ls_name = ["tom_sb","jack_sb","jane_sb","sb_richel"]
# def func(list):
# ret = []
# for name in list:
# if name.endswith("sb"):
# ret.append(name)
# return ret
# ret = func(ls_name)
# print(ret)
#输出:[‘tom_sb‘, ‘jack_sb‘, ‘jane_sb‘]
#此时如果想看谁是以sb 开头的,所以不太好
#==================================================
def abstract_func(func,list):
ret = []
for name in list:
if func(name):
ret.append(name)
return ret
def end_sb(name):
return name.endswith("sb")
ret = abstract_func(end_sb,ls_name)
# print(ret) #[‘tom_sb‘, ‘jack_sb‘, ‘jane_sb‘]
def start_sb(name):
return name.startswith("sb")
ret = abstract_func(start_sb,ls_name)
# print(ret) #[‘sb_richel‘]
#====================================
#和上面一样,这样就写活了
#和上面也一样,可以使用lambda匿名函数
ret = abstract_func(lambda x:x.startswith("sb"),ls_name)
# print(ret) #[‘sb_richel‘]
ret = abstract_func(lambda x:x.endswith("sb"),ls_name)
# print(ret) #[‘tom_sb‘, ‘jack_sb‘, ‘jane_sb‘]
#==========================牛逼
#终于可以引出内置函数filter() 了
ret= filter(lambda x:x.startswith("sb"),ls_name)
# print(ret) #<filter object at 0x000001C21F64B2E8>
# print(list(ret)) #[‘sb_richel‘]
ret = filter(lambda x:x.endswith("sb"),ls_name)
# print(list(ret)) #[‘tom_sb‘, ‘jack_sb‘, ‘jane_sb‘]
#=================================================
#=====================reduce======================
#=================================================
ls = [1,5,56,8,7,8,9,4,2,1,4]
# def func(arr):
# res = 0
# for num in arr:
# res +=num
# return res
# ret = func(ls)
# print(ret) #105
#现在想求累乘
#不太好
#===============================================
# def abstract_func(func,arr):
# res = 1
# for num in arr:
# res = func(res,num)
# return res
#但是res = 1 就写死了
#===============================================
# 改进:
def abstract_func(func,arr):
pop_num = arr.pop(0) #将第一个弹出来,并赋值给res
res = pop_num
for num in arr:
res = func(res,num)
arr.insert(0,pop_num) #恢复数据,不能随意修改原始数据
return res
# ret = abstract_func(lambda x,y:x+y,ls) #累加
#print(ret) #105
# ret = abstract_func(lambda x,y:x*y,ls) #累乘
# print(ret) #36126720
#=============================================
#如果再给个初始值
def abstract_func(func,arr,init_val = None):
if init_val != None:
res = init_val
else:
pop_num = arr.pop(0)
res = pop_num #将第一个弹出来,并赋值给res
for num in arr:
res = func(res,num)
if init_val == None:
arr.insert(0,pop_num)
return res
ret = abstract_func(lambda x,y:x+y,ls)
print(ret) #105
#其实这就是reduce() 函数
#python2中可以直接使用reduce
#python3中要引入模块
from functools import reduce
ret = reduce(lambda x,y:x+y,ls)
print(ret) #105
ret = reduce(lambda x,y:x+y,ls,100)
print(ret) #205
#这就是map reduce 和 filter 三个重要的内置函数 注:reduce在python3 中要引入.引入方法是from functools import reduce
2),其他内置函数:
abs(x, /):
Return the absolute value of the argument.
all(iterable, /):
Return True if bool(x) is True for all values x in the iterable。
If the iterable is empty, return True
print(all([1,2,3])) #True
print(all([0,1,2])) #False
any(iterable, /):
"""
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
"""
ascii(obj, /):
"""
Return an ASCII-only representation of an object.
ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串,
但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。
As repr(), return a string containing a printable representation of an
object, but escape the non-ASCII characters in the string returned by
repr() using \\x, \\u or \\U escapes. This generates a string similar
to that returned by repr() in Python 2.
"""
bin(number, /):
"""
Return the binary representation of an integer.
>>> bin(2796202)
‘0b1010101010101010101010‘
"""
callable(obj, /):
"""
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a
__call__() method.
"""
chr(i, /):
""" Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
:
"""
Compile source into a code object that can be executed by exec() or eval().
这个函数用来编译一段字符串的源码,结果可以生成字节码或者AST(抽像语法树),
字节码可以使用函数exec()来执行,而AST可以使用eval()来继续编译。
exec语句用来执行存储在代码对象、字符串、文件中的Python语句,eval语句用来计算存储在代码对象或字符串中的有效的Python表达式,
而compile语句则提供了字节编码的预编译。
当然,需要注意的是,使用exec和eval一定要注意安全性问题,尤其是网络环境中,可能给予他人执行非法语句的机会。
eval_code = compile("1+5","",‘eval‘)
a = eval(eval_code)
print(a) #6
exec_code = compile("for i in range(10): print(i)","","exec")
exec(exec_code)#这个不能用eval ,用exec可以 #0123456789
"""
delattr(obj, name, /):
"""
Deletes the named attribute from the given object.
delattr(x, ‘y‘) is equivalent to ``del x.y‘‘
"""
dir(...): ->[]
"""
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‘]
"""
divmod(x, y):
""" Return the tuple (x//y, x%y).
return (0, 0)
eval(source, globals=None, locals=None, /):
"""
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
exec(source, globals=None, locals=None, /):
"""
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
exit(i):
退出返回状态码
format(value, format_spec=‘‘, /):
"""
本函数把值value按format_spec的格式来格式化,然而函数解释format_spec是根据value的类型来决定的,不同的类型有不同的格式化解释。
当参数format_spec为空时,本函数等同于函数str(value)的方式。
其实本函数调用时,是把format(value, format_spec)的方式转换为type(value).__format__(format_spec)方式来调用,
因此在value类型里就查找方法__format__(),如果找不到此方法,就会返回异常TypeError。
例子:
print(format(‘helloworld‘, ‘<20‘))
print(format(‘helloworld‘, ‘>20‘))
print(format(‘helloworld‘, ‘^20‘))
s = "{:^20}".format("helloworld")
print(s)
‘‘‘
输出:
helloworld
helloworld
helloworld
helloworld
‘‘‘
参考博客:https://blog.csdn.net/caimouse/article/details/42010849
"""
getattr(object, name, default=None):
"""
getattr(object, name[, default]) -> value
"""
hasattr(obj, name, /):
"""
Return whether the object has an attribute with the given name.
hash(obj, /):
"""
Return the hash value for the given object.
help():
"""
help()进入帮助模式,help(object)查看具体某个对象的帮助文档
Define the builtin ‘help‘.
This is a wrapper around pydoc.help that provides a helpful message
when ‘help‘ is typed at the Python interactive prompt.
Calling help() at the Python prompt starts an interactive help session.
Calling help(thing) prints help for the python object ‘thing‘.
"""
hex(number, /):
"""
Return the hexadecimal representation of an integer.
>>> hex(12648430)
‘0xc0ffee‘
"""
id(obj, /):
"""
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object‘s memory address.)
"""
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
issubclass(cls, class_or_tuple, /)
Return whether ‘cls‘ is a derived from another class or is the same class.
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
or ...`` etc.
======================================================
iter(...)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
参考博客:https://blog.csdn.net/sxingming/article/details/51479039
Python常用内置类型和常用内置函数大汇总(更新中...)
原文:https://www.cnblogs.com/zach0812/p/11312479.html