1.3.2 經常使用內置函數

  經常使用內置函數(Built-In Functions,BIF)不須要導入任何模塊便可直接使用,在IDLE中執行以下命令能夠列出全部內置函數和內置對象,如代碼塊1.3.2.1所示:html

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.1python

  可使用 help(函數名) 查看某個函數的用法,不須要導入模塊就能夠直接使用 help(模塊名)查看該模塊的幫助文檔,例如 help('math')。help()函數示例,參考代碼塊1.3.2.2git

  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所示,其中方括號內的參數能夠忽略web

 
函數 功能簡要說明
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='\n',file=sql

sys.stdout,flush=False)shell

基本輸出函數 
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,macos

reverse=False)json

返回排序後的列表,其中iterable表示要排序的序列或迭代對象,key用來指定排序規則或依據,reverser用來指定升序或降序。該函數不改變iterable內任何元素的順序 
type(obj) 返回對象obj的類型 
zip(seq1[,seq2[...]]) 返回zip對象,其中元素爲(seqi[i],seq2[i],...)形式的元組

 

  小提示:api

    (1):能夠經過內置函數help()查看某個函數的使用幫助;app

    (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('請輸入您的年齡\n') 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的值爲函數名,咱們能夠自定義函數來決定以什麼樣的方式對序列中元素如何比較大小
相關文章
相關標籤/搜索