1.3.2 常用内置函数

  常用内置函数(Built-In Functions,BIF)不需要导入任何模块即可直接使用,在IDLE中执行如下命令可以列出所有内置函数和内置对象,如代码块1.3.2.1所示:

1 >>> dir(__builtins__)
2 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError',
'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError',
'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError',
'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning',
'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning',
'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__',
'__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes',
'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map',
'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr',
'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] 3 >>>

                              代码块1.3.2.1

  可以使用 help(函数名) 查看某个函数的用法,不需要导入模块就可以直接使用 help(模块名)查看该模块的帮助文档,例如 help('math')。help()函数示例,参考代码块1.3.2.2

  1 >>> help(abs)
  2 Help on built-in function abs in module builtins:
  3 
  4 abs(x, /)
  5     Return the absolute value of the argument.
  6 
  7 >>> 
  8 >>> 
  9 >>> help(math)
 10 Traceback (most recent call last):
 11   File "<pyshell#8>", line 1, in <module>
 12     help(math)
 13 NameError: name 'math' is not defined
 14 >>> 
 15 >>> help('math')
 16 Help on built-in module math:
 17 
 18 NAME
 19     math
 20 
 21 DESCRIPTION
 22     This module is always available.  It provides access to the
 23     mathematical functions defined by the C standard.
 24 
 25 FUNCTIONS
 26     acos(...)
 27         acos(x)
 28         
 29         Return the arc cosine (measured in radians) of x.
 30     
 31     acosh(...)
 32         acosh(x)
 33         
 34         Return the inverse hyperbolic cosine of x.
 35     
 36     asin(...)
 37         asin(x)
 38         
 39         Return the arc sine (measured in radians) of x.
 40     
 41     asinh(...)
 42         asinh(x)
 43         
 44         Return the inverse hyperbolic sine of x.
 45     
 46     atan(...)
 47         atan(x)
 48         
 49         Return the arc tangent (measured in radians) of x.
 50     
 51     atan2(...)
 52         atan2(y, x)
 53         
 54         Return the arc tangent (measured in radians) of y/x.
 55         Unlike atan(y/x), the signs of both x and y are considered.
 56     
 57     atanh(...)
 58         atanh(x)
 59         
 60         Return the inverse hyperbolic tangent of x.
 61     
 62     ceil(...)
 63         ceil(x)
 64         
 65         Return the ceiling of x as an Integral.
 66         This is the smallest integer >= x.
 67     
 68     copysign(...)
 69         copysign(x, y)
 70         
 71         Return a float with the magnitude (absolute value) of x but the sign 
 72         of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
 73         returns -1.0.
 74     
 75     cos(...)
 76         cos(x)
 77         
 78         Return the cosine of x (measured in radians).
 79     
 80     cosh(...)
 81         cosh(x)
 82         
 83         Return the hyperbolic cosine of x.
 84     
 85     degrees(...)
 86         degrees(x)
 87         
 88         Convert angle x from radians to degrees.
 89     
 90     erf(...)
 91         erf(x)
 92         
 93         Error function at x.
 94     
 95     erfc(...)
 96         erfc(x)
 97         
 98         Complementary error function at x.
 99     
100     exp(...)
101         exp(x)
102         
103         Return e raised to the power of x.
104     
105     expm1(...)
106         expm1(x)
107         
108         Return exp(x)-1.
109         This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
110     
111     fabs(...)
112         fabs(x)
113         
114         Return the absolute value of the float x.
115     
116     factorial(...)
117         factorial(x) -> Integral
118         
119         Find x!. Raise a ValueError if x is negative or non-integral.
120     
121     floor(...)
122         floor(x)
123         
124         Return the floor of x as an Integral.
125         This is the largest integer <= x.
126     
127     fmod(...)
128         fmod(x, y)
129         
130         Return fmod(x, y), according to platform C.  x % y may differ.
131     
132     frexp(...)
133         frexp(x)
134         
135         Return the mantissa and exponent of x, as pair (m, e).
136         m is a float and e is an int, such that x = m * 2.**e.
137         If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
138     
139     fsum(...)
140         fsum(iterable)
141         
142         Return an accurate floating point sum of values in the iterable.
143         Assumes IEEE-754 floating point arithmetic.
144     
145     gamma(...)
146         gamma(x)
147         
148         Gamma function at x.
149     
150     gcd(...)
151         gcd(x, y) -> int
152         greatest common divisor of x and y
153     
154     hypot(...)
155         hypot(x, y)
156         
157         Return the Euclidean distance, sqrt(x*x + y*y).
158     
159     isclose(...)
160         isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool
161         
162         Determine whether two floating point numbers are close in value.
163         
164            rel_tol
165                maximum difference for being considered "close", relative to the
166                magnitude of the input values
167             abs_tol
168                maximum difference for being considered "close", regardless of the
169                magnitude of the input values
170         
171         Return True if a is close in value to b, and False otherwise.
172         
173         For the values to be considered close, the difference between them
174         must be smaller than at least one of the tolerances.
175         
176         -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
177         is, NaN is not close to anything, even itself.  inf and -inf are
178         only close to themselves.
179     
180     isfinite(...)
181         isfinite(x) -> bool
182         
183         Return True if x is neither an infinity nor a NaN, and False otherwise.
184     
185     isinf(...)
186         isinf(x) -> bool
187         
188         Return True if x is a positive or negative infinity, and False otherwise.
189     
190     isnan(...)
191         isnan(x) -> bool
192         
193         Return True if x is a NaN (not a number), and False otherwise.
194     
195     ldexp(...)
196         ldexp(x, i)
197         
198         Return x * (2**i).
199     
200     lgamma(...)
201         lgamma(x)
202         
203         Natural logarithm of absolute value of Gamma function at x.
204     
205     log(...)
206         log(x[, base])
207         
208         Return the logarithm of x to the given base.
209         If the base not specified, returns the natural logarithm (base e) of x.
210     
211     log10(...)
212         log10(x)
213         
214         Return the base 10 logarithm of x.
215     
216     log1p(...)
217         log1p(x)
218         
219         Return the natural logarithm of 1+x (base e).
220         The result is computed in a way which is accurate for x near zero.
221     
222     log2(...)
223         log2(x)
224         
225         Return the base 2 logarithm of x.
226     
227     modf(...)
228         modf(x)
229         
230         Return the fractional and integer parts of x.  Both results carry the sign
231         of x and are floats.
232     
233     pow(...)
234         pow(x, y)
235         
236         Return x**y (x to the power of y).
237     
238     radians(...)
239         radians(x)
240         
241         Convert angle x from degrees to radians.
242     
243     sin(...)
244         sin(x)
245         
246         Return the sine of x (measured in radians).
247     
248     sinh(...)
249         sinh(x)
250         
251         Return the hyperbolic sine of x.
252     
253     sqrt(...)
254         sqrt(x)
255         
256         Return the square root of x.
257     
258     tan(...)
259         tan(x)
260         
261         Return the tangent of x (measured in radians).
262     
263     tanh(...)
264         tanh(x)
265         
266         Return the hyperbolic tangent of x.
267     
268     trunc(...)
269         trunc(x:Real) -> Integral
270         
271         Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.
272 
273 DATA
274     e = 2.718281828459045
275     inf = inf
276     nan = nan
277     pi = 3.141592653589793
278 
279 FILE
280     (built-in)
281 
282 
283 >>> 
代码块1.3.2.2

  常用内置函数及其功能简要说明如表1.3.2.3所示,其中方括号内的参数可以忽略

 
函数 功能简要说明
abs(x) 返回数字 x 的绝对值或复数的模
all(iterable) 如果对于可迭代对象iterable中所有元素 x 都有 bool(x) 为 True,则返回 True。对于空的可迭代对象也返回 True
any(iterable) 只要可迭代iterable中存在元素x使得bool(x)为True,则返回True。对于空的可迭代对象返回False
bin(x) 将数字x转换为二进制
bool(x) 返回与x等价的布尔值 True 或 False
callable(object) 测试对象object是否可调用,类和函数是可调用的,包含__call__()方法的类的对象也是可调用的
compile() 用于把Python代码编译成可被 exec() 或 eval() 函数执行的代码对象
chr(x) 返回Unicode编码为x的字符 
dir(obj) 返回指定对象obj或模块obj的成员列表 
eval(s[,globals[,locals]])  计算并返回字符串 s 中表达式的值
exec(x)   执行代码或代码对象 x 
filter(func,seq)  返回filter对象,其中包含序列seq中使得单参数函数func返回值为True的那些元素,如果函数func为None则返回那些值等价于True的元素 
float(x)  把数字或字符串x转换为浮点数并返回
hasattr(obj,name)    测试对象obj是否具有成员name 
hash(x) 返回对象 x 的哈希值,如果 x 不可哈希则抛出异常 
help(obj) 返回对象obj的帮助信息 
hex(x) 把数字x转换为十六进制 
id(obj) 返回对象obj的帮助信息 
input([提示内容字符串]) 接收键盘输入的内容,返回字符串 
int(x[,d]) 返回数字x的整数部分,或把d进制的字符串转换为十进制并返回,d默认为十进制 
isinstance(object,class-or-type-or-tuple)  测试对象object是否属于指定类型(如果有多个类型的话需要放到tuple中)的实例
len(obj)  返回对象obj包含的元素个数,适用于列表、元组、集合、字典、字符串、range对象和其他可迭代类型的对象 
list([x])、set([x])、tuple([x])、dict([x]) 把对象x转换为列表、集合、元组、或字典并返回,或生成空列表、空集合、空元组、空字典
map(func,seq) 将函数func映射至序列seq中每个元素,返回包含函数值的map对象 
max(x)、min(x) 返回序列x中的最大值、最小值,要求序列x中的所有元素之间可比较大小 
next(x) 返回可迭代对象x中的下一个元素 
sum(x) 返回序列x中所有元素之和,要求序列x中的所有元素必须为数字 
oct(x) 把数字x转换为八进制 
open(name[,mode]) 以指定模式mode打开文件name并返回文件对象 
ord(x)   返回一个字符x的Unicode编码 
pow(x,y) 返回x的y次方,等价于x **y 

print(value,...,sep='',end=' ',file=

sys.stdout,flush=False)

基本输出函数 
range([start,]end[,step]) 返回range对象,其中包含(start,end)区间以步长的整数 
reduce(func,seq) 将双参数的函数func以迭代的方式从左到右依次应用至序列seq中每个元素,最终返回单个值作为结果。在Python3版本中需要从functools模块中导入reduce函数再使用
reversed(seq) 返回seq(可以是列表、元组、字符串、range以及其他可迭代对象)中所有元素逆序后的迭代器对象 
round(x[,小数位数]) 对x进行四舍五入,若不指定小数位数,则返回整数 
str(obj) 把对象obj直接转换为字符串 

sorted(iterbale,key=None,

reverse=False)

返回排序后的列表,其中iterable表示要排序的序列或迭代对象,key用来指定排序规则或依据,reverser用来指定升序或降序。该函数不改变iterable内任何元素的顺序 
type(obj) 返回对象obj的类型 
zip(seq1[,seq2[...]]) 返回zip对象,其中元素为(seqi[i],seq2[i],...)形式的元组

  小提示:

    (1):可以通过内置函数help()查看某个函数的使用帮助;

    (2):编写程序时应优先考虑使用内置函数,因为内置函数不仅程序、稳定,而且速度相对较快;

    (3):可以导入sys模块后使用print(sys.builtin_module_names)查看Python所有内置模块名称;

1 >>> import sys
2 >>> 
3 >>> print(sys.builtin_module_names)
4 ('_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha512', '_signal', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
5 >>> 

    (4):可以使用help('modules')查看本机所有可用模块名称。

help('modules')
 1 >>> help('modules')
 2 
 3 Please wait a moment while I gather a list of all available modules...
 4 
 5 AutoComplete        _pydecimal          ensurepip           pydoc
 6 AutoCompleteWindow  _pyio               enum                pydoc_data
 7 AutoExpand          _random             errno               pyexpat
 8 Bindings            _sha1               faulthandler        queue
 9 CallTipWindow       _sha256             filecmp             quopri
10 CallTips            _sha512             fileinput           random
11 ClassBrowser        _signal             fnmatch             re
12 CodeContext         _sitebuiltins       formatter           reprlib
13 ColorDelegator      _socket             fractions           rlcompleter
14 Debugger            _sqlite3            ftplib              rpc
15 Delegator           _sre                functools           run
16 EditorWindow        _ssl                gc                  runpy
17 FileList            _stat               genericpath         sched
18 FormatParagraph     _string             getopt              select
19 GrepDialog          _strptime           getpass             selectors
20 HyperParser         _struct             gettext             setuptools
21 IOBinding           _symtable           glob                shelve
22 IdleHistory         _testbuffer         gzip                shlex
23 MultiCall           _testcapi           hashlib             shutil
24 MultiStatusBar      _testimportmultiple heapq               signal
25 ObjectBrowser       _testmultiphase     help                site
26 OutputWindow        _thread             hmac                smtpd
27 ParenMatch          _threading_local    html                smtplib
28 PathBrowser         _tkinter            http                sndhdr
29 Percolator          _tracemalloc        idle                socket
30 PyParse             _warnings           idle_test           socketserver
31 PyShell             _weakref            idlelib             sqlite3
32 RemoteDebugger      _weakrefset         idlever             sre_compile
33 RemoteObjectBrowser _winapi             imaplib             sre_constants
34 ReplaceDialog       abc                 imghdr              sre_parse
35 RstripExtension     aboutDialog         imp                 ssl
36 ScriptBinding       aifc                importlib           stat
37 ScrolledList        antigravity         inspect             statistics
38 SearchDialog        argparse            io                  string
39 SearchDialogBase    array               ipaddress           stringprep
40 SearchEngine        ast                 itertools           struct
41 StackViewer         asynchat            json                subprocess
42 ToolTip             asyncio             keybindingDialog    sunau
43 TreeWidget          asyncore            keyword             symbol
44 UndoDelegator       atexit              lib2to3             symtable
45 WidgetRedirector    audioop             linecache           sys
46 WindowList          base64              locale              sysconfig
47 ZoomHeight          bdb                 logging             tabbedpages
48 __future__          binascii            lzma                tabnanny
49 __main__            binhex              macosxSupport       tarfile
50 _ast                bisect              macpath             telnetlib
51 _bisect             builtins            macurl2path         tempfile
52 _bootlocale         bz2                 mailbox             test
53 _bz2                cProfile            mailcap             textView
54 _codecs             calendar            marshal             textwrap
55 _codecs_cn          cgi                 math                this
56 _codecs_hk          cgitb               mimetypes           threading
57 _codecs_iso2022     chunk               mmap                time
58 _codecs_jp          cmath               modulefinder        timeit
59 _codecs_kr          cmd                 msilib              tkinter
60 _codecs_tw          code                msvcrt              token
61 _collections        codecs              multiprocessing     tokenize
62 _collections_abc    codeop              netrc               trace
63 _compat_pickle      collections         nntplib             traceback
64 _compression        colorsys            nt                  tracemalloc
65 _csv                compileall          ntpath              tty
66 _ctypes             concurrent          nturl2path          turtle
67 _ctypes_test        configDialog        numbers             turtledemo
68 _datetime           configHandler       opcode              types
69 _decimal            configHelpSourceEdit operator            typing
70 _dummy_thread       configSectionNameDialog optparse            unicodedata
71 _elementtree        configparser        os                  unittest
72 _functools          contextlib          parser              urllib
73 _hashlib            copy                pathlib             uu
74 _heapq              copyreg             pdb                 uuid
75 _imp                crypt               pickle              venv
76 _io                 csv                 pickletools         warnings
77 _json               ctypes              pip                 wave
78 _locale             curses              pipes               weakref
79 _lsprof             datetime            pkg_resources       webbrowser
80 _lzma               dbm                 pkgutil             winreg
81 _markupbase         decimal             platform            winsound
82 _md5                difflib             plistlib            wsgiref
83 _msi                dis                 poplib              xdrlib
84 _multibytecodec     distutils           posixpath           xml
85 _multiprocessing    doctest             pprint              xmlrpc
86 _opcode             dummy_threading     profile             xxsubtype
87 _operator           dynOptionMenuWidget pstats              zipapp
88 _osx_support        easy_install        pty                 zipfile
89 _overlapped         email               py_compile          zipimport
90 _pickle             encodings           pyclbr              zlib
91 
92 Enter any module name to get more help.  Or, type "modules spam" to search
93 for modules whose name or summary contain the string "spam".
94 
95 >>> 

  

  本节练习代码如下:要听董老师的,不要眼高手低,一定要动手练习,遇到不懂的可以自己百度一下。

  1 =========================abs(x)
  2 >>> abs(-3)             #返回数字的绝对值
  3 3
  4 >>> 
  5 >>> abs(3 + 5j)       #返回复数的模
  6 5.830951894845301
  7 >>> 
  8 
  9 =========================all(iterable)  
 10 >>> all('12306')          #字符串是可迭代对象,'12306'的所有元素 x 都有 bool(x) 为 True,故返回 True
 11 True
 12 >>> bool('0')
 13 True
 14 >>> 
 15 >>> all(['',None])        #列表也是可迭代对象,但其中的元素''和None 的bool结果都是False,所以all() 返回False
 16 False
 17 >>> 
 18 >>> bool('')
 19 False
 20 >>> bool(None)
 21 False
 22 >>> 
 23 >>> all('')                  #空的可迭代对象也返回True
 24 True
 25 >>> 
 26 
 27 =========================any(iterable)
 28 >>> any(['',None,1])   #虽然bool('')、bool(None)为False,单bool(1)为True ,故any()返回True
 29 True
 30 >>> 
 31 >>> any('')                #空的可迭代对象返回False
 32 False
 33 >>> 
 34 
 35 =========================bin(x)
 36 >>> bin(2)               #看来bin()的参数只能是正负整数,不能是浮点数
 37 '0b10'
 38 >>> bin(-2)
 39 '-0b10'
 40 >>> bin(2.1)
 41 Traceback (most recent call last):
 42   File "<pyshell#55>", line 1, in <module>
 43     bin(2.1)
 44 TypeError: 'float' object cannot be interpreted as an integer
 45 >>> 
 46 
 47 =========================bool(x)
 48 >>> bool(1)
 49 True
 50 >>> bool(1.1)
 51 True
 52 >>> bool(-1)
 53 True
 54 >>> bool(1 + j)
 55 Traceback (most recent call last):
 56   File "<pyshell#64>", line 1, in <module>
 57     bool(1 + j)
 58 NameError: name 'j' is not defined
 59 >>> 
 60 >>> bool(0)
 61 False
 62 >>> 
 63 >>> bool('s')
 64 True
 65 >>> bool('')
 66 False
 67 
 68 总结:bool()函数返回False的三种情况:数值0、空的可迭代对象、None,其他对象返回True。
 69 
 70 =========================callable(object)
 71 >>> def myfun():
 72     pass
 73 
 74 >>> 
 75 >>> class Mycls():
 76     pass
 77 
 78 >>> 
 79 >>> m = Mycls()        
 80 >>> 
 81 >>> callable(myfun)
 82 True
 83 >>> callable(Mycls)
 84 True
 85 >>> callable(m)           #因为m对象没有__callable__()方法,故返回False
 86 False
 87 >>> 
 88 >>> m.__call__():
 89     
 90 SyntaxError: invalid syntax
 91 >>> m.__call__()
 92 Traceback (most recent call last):
 93   File "<pyshell#111>", line 1, in <module>
 94     m.__call__()
 95 AttributeError: 'Mycls' object has no attribute '__call__'
 96 >>> 
 97 
 98 =========================compile()
 99 >>> s = "print('hello world')"
100 >>> ss = compile(s,'','single')
101 >>> ss
102 <code object <module> at 0x00000000034E1660, file "", line 1>
103 >>> 
104 >>> exec(ss)
105 hello world
106 
107 
108 格式:compile( str, file, type )
109 
110 compile语句是从type类型(包括’eval’: 配合eval使用,’single’: 配合单一语句的exec使用,’exec’: 配合多语句的exec使用)中将str里面的语句创建成代码对象。
111 file是代码存放的地方,通常为”。
112 
113 拓展一篇文章:
114 标题:Python可执行对象——exec、eval、compile 
115 URL:http://www.pythoner.com/56.html
116 
117 
118 =========================chr()
119 >>> chr(11)     #参数一定要是正整数,
120 'x0b' 
121 >>> 
122 >>> 
123 >>> chr(97)
124 'a'
125 >>> 
126 >>> chr(200)
127 'è'
128 >>> 
129 
130 
131 =========================dir(obj)
132 #根据说明,obj可以是Python的对象也可以是模块
133 >>> class Student():
134     def __init__(self,name):
135         self.name = name
136 
137 >>> 
138 >>> dir(Student)      #Student是Python的对象
139 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
140 >>> 
141 >>> 
142 >>> dir('math')        #math是模块
143 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
144 >>> 
145 
146 
147 =========================eval(s[,globals[,locals]])
148 >>> d = {'ph':1}
149 >>> eval('ph + 3',d)
150 4
151 >>> 
152 
153 
154 拓展URL:https://www.cnblogs.com/sesshoumaru/p/5995712.html
155 
156 
157 =========================exec(x)
158 exec函数和eval函数类似,也是执行动态语句,只不过eval函数只用于执行表达式求值,而exec函数主要用于执行语句块。
159 
160 >>> s = 'a = 1 + 1'
161 >>> exec(s)
162 >>> a
163 2
164 
165 拓展URL:https://www.cnblogs.com/sesshoumaru/p/5998523.html
166 
167 
168 =========================filter(func,seq)
169 #filter有两个参数,func为函数,seq为序列
170 >>> def func(x):               
171     return x % 2 ==0
172 
173 >>> 
174 >>> seq = range(0,20)
175 >>> 
176 >>> 
177 >>> f = filter(func,seq)                  #注意第一个参数为函数名,表示的是func这个对象,func()的话会限制性函数,将函数返回值作为filter()的第一个参数,这点要切记
178 >>> list(f)
179 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
180 >>> 
181 
182 
183 =========================float(x)
184 >>> float(2)
185 2.0
186 >>> 
187 >>> float('1')
188 1.0
189 >>> float('1.0')
190 1.0
191 >>> 
192 
193 
194 =========================hasattr(obj,name)
195 >>> class Student():
196     def __init__(self,name,age):
197         self.name = name
198         self.age = age
199 
200         
201 >>> 
202 >>> hasattr(Student,'name')
203 False
204 >>> 
205 >>> s = Student('zhangsan',10)
206 >>> hasattr(s,'name')
207 True                                               #说明这个name属性是属于Student的具体的对象的,而非类的,当然类也可有自己的属性,给Student再加一个属性看看
208 >>>
209 >>> class Student():
210     count = 0
211     def __init__(self,name,age):
212         self.name = name
213         self.age = age
214 
215         
216 >>> hasattr(Student,'count')
217 True
218 >>> 
219 >>> s = Student('lisi','20')
220 >>> hasattr(s,'count')               #看来类的属性,也属于其子类。我们可以用这个类属性count统计一共实例化了多少次
221 True
222 >>> 
223 
224 
225 #Student每实例化一次,count的值就会加1
226 >>> class Student():
227     count = 0
228     def __init__(self,name,age):
229         self.name = name
230         self.age = age
231         Student.count += 1
232 
233         
234 >>> 
235 >>> s1 = Student('11',11)
236 >>> s2 = Student('22',22)
237 >>> 
238 >>> s2.count
239 2
240 >>> s1.count
241 2
242 >>> Student.count
243 2 
244 
245 
246 =========================hex(x)
247 >>> a = 33
248 >>> hex(a)
249 '0x21'
250 >>> 
251 
252 
253 =========================input([提示内容字符串])
254 >>> a = input('请输入您的年龄
')
255 请输入您的年龄
256 18
257 >>> a
258 '18'
259 >>> int(a)
260 18
261 >>> float(a)
262 18.0
263 >>> 
264 >>> #虽然input返回的是字符串,但是我们能对字符串进行处理啊
265 
266 
267 =========================int(x[,d])
268 >>> b = '33'
269 >>> b1 = int(b)
270 >>> b1
271 33
272 >>> 
273 >>> #假设b是六进制的,转换为十进制的方法
274 >>> 
275 >>> b2 = int(b,6)
276 >>> b2
277 21
278 >>> 
279 
280 =========================isinstance(object,class-or-type-or-tuple)
281 >>> isinstance(2,int)
282 True
283 >>> isinstance(s,Student)
284 False
285 >>> 
286 >>> isinstance('2',(int,float,str))
287 True
288 >>> 
289 
290 
291 
292 =========================map(func,seq)
293 #演示一个将字符串'123.456'转换成数字123.456
294 
295 from functools import reduce
296 
297 def str2num(s):
298     d = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'.':'.'}
299     return d[s]
300 
301 def get_num(x,y):
302     return x*10 + y
303 
304 def changestr(mys):
305 
306     l=[]
307     if '.' in mys:
308         l = mys.split('.')
309     else:
310         l.append(mys)
311 
312     print('ll:{}'.format(l))
313 
314     if len(l) == 1:
315         ll = map(str2num,l[0])
316         num = reduce(get_num,ll)
317         return num
318 
319     elif len(l) == 2:
320         ll = []
321         for i in l:
322             li = map(str2num,i)
323             ll += li
324         num = reduce(get_num, ll)
325         cf = len(mys) - mys.index('.') - 1
326         return num / 10 ** cf
327 
328     else:
329         print('空字符串还处理啥呢,结束吧')
330 
331 
332 if __name__ == '__main__':
333     mys = '123.456'
334     print(changestr(mys))
335 
336 #执行结果:123.456
337 
338 #我在网上找的别人的实现过程,代码就简短的多了,看着真舒服
339 from functools import reduce
340 from math import pow
341 def char2num(s):
342     digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
343     return digits[s]
344 
345 def str2float(s):
346     l = len(s.split('.')[1])
347     s = s.replace('.','')
348     return reduce(lambda x,y:10*x+y,map(char2num,s))/pow(10,l)
349 
350 
351 =========================range([start,]end[,step])
352 >>> range(0,5)
353 range(0, 5)
354 >>> 
355 >>> 
356 >>> range(5)      #start参数的默认值为0
357 range(0, 5)
358 >>> 
359 >>> range(0,100,10)
360 range(0, 100, 10)
361 >>> 
362 >>> list(range(0,100,10))
363 [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
364 >>> 
365 
366 
367 =========================reversed(seq)
368 >>> l = list(range(0,10))
369 >>> l
370 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
371 >>> 
372 >>> ll = list(reversed(l))       #因为是返回的迭代器对象,可以将其转换为list,当然也可以转换为tuple,
373 >>> ll
374 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
375 >>> 
376 >>> l
377 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]     #说明经过reversed()函数的转换,是不影响原序列的元素顺序的哦
378 
379 
380 
381 =========================round(x[,小数位数]) 
382 >>> a = 1   
383 >>> b = 1.4 
384 >>> c = 1.5 
385 >>>         
386 >>> round(1)
387 1           
388 >>> round(b)
389 1           
390 >>> round(c)
391 2           
392 >>>         
393 
394 
395 
396 =========================sorted(iterbale,key=None,reverse=False)           
397 #sorted() 函数的关键应该是key,,以什么规则进行排序
398 
399 有一组学成的名字和成绩如下:
400 L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
401 
402 任务一:请用sorted()对上述列表分别按名字排序:
403 
404 L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
405 
406 def by_name(x):
407     return x[0]
408 
409 L2 = sorted(L, key=by_name)
410 
411 print(L2)
412 
413 #执行结果:[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
414 
415 
416 任务二:按成绩从高到低排序:
417 我的代码:
418 
419 def to_num(x):
420     return x[1]
421 
422 lll = sorted(L,key=to_num,reverse=True)
423 print(lll)  #[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
424 
425 
426 #结合着两个例子,可以看出,key是要定义一个函数,如何处理第一个参数中的元素,这个是制定排序标准,自定义按什么排序。
427 
428 
429 
430 =========================zip(seq1[,seq2[...]])
431 
432 a1 = [1,2,3]
433 a2 = [4,5,6,7]
434 a3 = [7,8,9]
435 a4 = ["a","b","c","d"]
436 
437 zip1=zip(a1,a2,a3,a4)
438 
439 for z in zip1:
440     print(z)
441 
442 #执行结果如下:
443 (1, 4, 7, 'a')
444 (2, 5, 8, 'b')
445 (3, 6, 9, 'c')
446 
447 #观察结果可以发现,zip1中的元素个数是zip()中序列中元素最少的那个序列的元素个数决定。
448 
449 
450 =========================max(x)
451 #max()函数还有一个key参数,可以指定比较大小的一句,比如:
452 max(['2','111'],key=len)
453 返回值为'111'
454 这个key的值为函数名,我们可以自定义函数来决定以什么样的方式对序列中元素如何比较大小
原文地址:https://www.cnblogs.com/avention/p/8504712.html