古墓派掌门 阅读(68) 评论(0)

内置函数

Built-in Functions
abs() dict() help() min() setattr()
all()  dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
bytearray() filter() issubclass() pow() super()
delattr() hash() memoryview() set  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数。

内置函数分类

 

 

 

 

作用域相关

 

 

基于字典的形式获取局部变量和全局变量

globals()——获取全局变量的字典

locals()——获取执行本方法所在命名空间内的局部变量的字典

其他

 

 

 

 

输入输出相关

 input()输入

s = input("请输入内容 : ")  #输入的内容赋值给s变量
print(s)  #输入什么打印什么。数据类型是str
input用法

print输出

1 def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
2     """
3     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
4     file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
5     sep:   打印多个值之间的分隔符,默认为空格
6     end:   每一次打印的结尾,默认为换行符
7     flush: 立即把内容输出到流文件,不作缓存
8     """
print源码剖析
1 f = open('tmp_file','w')
2 print(123,456,sep=',',file = f,flush=True)
file关键字说明
1 from time import sleep
2 for i in range(0,101,2):
3     sleep(0.1)
4     str="*"*(i//2)
5     print('\r%s%%:%s'%(i,str),end="",flush=True)
打印进度条

数据类型相关

type(s)返回s的数据类型

s="abc"
print(type(s))#<class 'str'>
type说明

内存相关

id(s) s是参数,返回一个变量的内存地址

hash(s) s是参数,返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

1 l1=[1,2,3]
2 l2=(1,2,3)
3 print(hash(l2))#2528502973977326415
4 print(hash(l1))#TypeError: unhashable type: 'list'
hash举例

hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字。

*每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变。

文件操作相关

open()  打开一个文件,返回一个文件操作符(文件句柄)

操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)

可以用encoding指定编码.

模块操作相关

__import__导入一个模块

os = __import__('os')
print(os.path.abspath('.'))
__import__

帮助方法

help(s)  s为函数名

  1 help(str)
  2 
  3 
  4 #输出
  5 class str(object)
  6  |  str(object='') -> str
  7  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
  8  |  
  9  |  Create a new string object from the given object. If encoding or
 10  |  errors is specified, then the object must expose a data buffer
 11  |  that will be decoded using the given encoding and error handler.
 12  |  Otherwise, returns the result of object.__str__() (if defined)
 13  |  or repr(object).
 14  |  encoding defaults to sys.getdefaultencoding().
 15  |  errors defaults to 'strict'.
 16  |  
 17  |  Methods defined here:
 18  |  
 19  |  __add__(self, value, /)
 20  |      Return self+value.
 21  |  
 22  |  __contains__(self, key, /)
 23  |      Return key in self.
 24  |  
 25  |  __eq__(self, value, /)
 26  |      Return self==value.
 27  |  
 28  |  __format__(...)
 29  |      S.__format__(format_spec) -> str
 30  |      
 31  |      Return a formatted version of S as described by format_spec.
 32  |  
 33  |  __ge__(self, value, /)
 34  |      Return self>=value.
 35  |  
 36  |  __getattribute__(self, name, /)
 37  |      Return getattr(self, name).
 38  |  
 39  |  __getitem__(self, key, /)
 40  |      Return self[key].
 41  |  
 42  |  __getnewargs__(...)
 43  |  
 44  |  __gt__(self, value, /)
 45  |      Return self>value.
 46  |  
 47  |  __hash__(self, /)
 48  |      Return hash(self).
 49  |  
 50  |  __iter__(self, /)
 51  |      Implement iter(self).
 52  |  
 53  |  __le__(self, value, /)
 54  |      Return self<=value.
 55  |  
 56  |  __len__(self, /)
 57  |      Return len(self).
 58  |  
 59  |  __lt__(self, value, /)
 60  |      Return self<value.
 61  |  
 62  |  __mod__(self, value, /)
 63  |      Return self%value.
 64  |  
 65  |  __mul__(self, value, /)
 66  |      Return self*value.n
 67  |  
 68  |  __ne__(self, value, /)
 69  |      Return self!=value.
 70  |  
 71  |  __new__(*args, **kwargs) from builtins.type
 72  |      Create and return a new object.  See help(type) for accurate signature.
 73  |  
 74  |  __repr__(self, /)
 75  |      Return repr(self).
 76  |  
 77  |  __rmod__(self, value, /)
 78  |      Return value%self.
 79  |  
 80  |  __rmul__(self, value, /)
 81  |      Return self*value.
 82  |  
 83  |  __sizeof__(...)
 84  |      S.__sizeof__() -> size of S in memory, in bytes
 85  |  
 86  |  __str__(self, /)
 87  |      Return str(self).
 88  |  
 89  |  capitalize(...)
 90  |      S.capitalize() -> str
 91  |      
 92  |      Return a capitalized version of S, i.e. make the first character
 93  |      have upper case and the rest lower case.
 94  |  
 95  |  casefold(...)
 96  |      S.casefold() -> str
 97  |      
 98  |      Return a version of S suitable for caseless comparisons.
 99  |  
100  |  center(...)
101  |      S.center(width[, fillchar]) -> str
102  |      
103  |      Return S centered in a string of length width. Padding is
104  |      done using the specified fill character (default is a space)
105  |  
106  |  count(...)
107  |      S.count(sub[, start[, end]]) -> int
108  |      
109  |      Return the number of non-overlapping occurrences of substring sub in
110  |      string S[start:end].  Optional arguments start and end are
111  |      interpreted as in slice notation.
112  |  
113  |  encode(...)
114  |      S.encode(encoding='utf-8', errors='strict') -> bytes
115  |      
116  |      Encode S using the codec registered for encoding. Default encoding
117  |      is 'utf-8'. errors may be given to set a different error
118  |      handling scheme. Default is 'strict' meaning that encoding errors raise
119  |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
120  |      'xmlcharrefreplace' as well as any other name registered with
121  |      codecs.register_error that can handle UnicodeEncodeErrors.
122  |  
123  |  endswith(...)
124  |      S.endswith(suffix[, start[, end]]) -> bool
125  |      
126  |      Return True if S ends with the specified suffix, False otherwise.
127  |      With optional start, test S beginning at that position.
128  |      With optional end, stop comparing S at that position.
129  |      suffix can also be a tuple of strings to try.
130  |  
131  |  expandtabs(...)
132  |      S.expandtabs(tabsize=8) -> str
133  |      
134  |      Return a copy of S where all tab characters are expanded using spaces.
135  |      If tabsize is not given, a tab size of 8 characters is assumed.
136  |  
137  |  find(...)
138  |      S.find(sub[, start[, end]]) -> int
139  |      
140  |      Return the lowest index in S where substring sub is found,
141  |      such that sub is contained within S[start:end].  Optional
142  |      arguments start and end are interpreted as in slice notation.
143  |      
144  |      Return -1 on failure.
145  |  
146  |  format(...)
147  |      S.format(*args, **kwargs) -> str
148  |      
149  |      Return a formatted version of S, using substitutions from args and kwargs.
150  |      The substitutions are identified by braces ('{' and '}').
151  |  
152  |  format_map(...)
153  |      S.format_map(mapping) -> str
154  |      
155  |      Return a formatted version of S, using substitutions from mapping.
156  |      The substitutions are identified by braces ('{' and '}').
157  |  
158  |  index(...)
159  |      S.index(sub[, start[, end]]) -> int
160  |      
161  |      Return the lowest index in S where substring sub is found, 
162  |      such that sub is contained within S[start:end].  Optional
163  |      arguments start and end are interpreted as in slice notation.
164  |      
165  |      Raises ValueError when the substring is not found.
166  |  
167  |  isalnum(...)
168  |      S.isalnum() -> bool
169  |      
170  |      Return True if all characters in S are alphanumeric
171  |      and there is at least one character in S, False otherwise.
172  |  
173  |  isalpha(...)
174  |      S.isalpha() -> bool
175  |      
176  |      Return True if all characters in S are alphabetic
177  |      and there is at least one character in S, False otherwise.
178  |  
179  |  isdecimal(...)
180  |      S.isdecimal() -> bool
181  |      
182  |      Return True if there are only decimal characters in S,
183  |      False otherwise.
184  |  
185  |  isdigit(...)
186  |      S.isdigit() -> bool
187  |      
188  |      Return True if all characters in S are digits
189  |      and there is at least one character in S, False otherwise.
190  |  
191  |  isidentifier(...)
192  |      S.isidentifier() -> bool
193  |      
194  |      Return True if S is a valid identifier according
195  |      to the language definition.
196  |      
197  |      Use keyword.iskeyword() to test for reserved identifiers
198  |      such as "def" and "class".
199  |  
200  |  islower(...)
201  |      S.islower() -> bool
202  |      
203  |      Return True if all cased characters in S are lowercase and there is
204  |      at least one cased character in S, False otherwise.
205  |  
206  |  isnumeric(...)
207  |      S.isnumeric() -> bool
208  |      
209  |      Return True if there are only numeric characters in S,
210  |      False otherwise.
211  |  
212  |  isprintable(...)
213  |      S.isprintable() -> bool
214  |      
215  |      Return True if all characters in S are considered
216  |      printable in repr() or S is empty, False otherwise.
217  |  
218  |  isspace(...)
219  |      S.isspace() -> bool
220  |      
221  |      Return True if all characters in S are whitespace
222  |      and there is at least one character in S, False otherwise.
223  |  
224  |  istitle(...)
225  |      S.istitle() -> bool
226  |      
227  |      Return True if S is a titlecased string and there is at least one
228  |      character in S, i.e. upper- and titlecase characters may only
229  |      follow uncased characters and lowercase characters only cased ones.
230  |      Return False otherwise.
231  |  
232  |  isupper(...)
233  |      S.isupper() -> bool
234  |      
235  |      Return True if all cased characters in S are uppercase and there is
236  |      at least one cased character in S, False otherwise.
237  |  
238  |  join(...)
239  |      S.join(iterable) -> str
240  |      
241  |      Return a string which is the concatenation of the strings in the
242  |      iterable.  The separator between elements is S.
243  |  
244  |  ljust(...)
245  |      S.ljust(width[, fillchar]) -> str
246  |      
247  |      Return S left-justified in a Unicode string of length width. Padding is
248  |      done using the specified fill character (default is a space).
249  |  
250  |  lower(...)
251  |      S.lower() -> str
252  |      
253  |      Return a copy of the string S converted to lowercase.
254  |  
255  |  lstrip(...)
256  |      S.lstrip([chars]) -> str
257  |      
258  |      Return a copy of the string S with leading whitespace removed.
259  |      If chars is given and not None, remove characters in chars instead.
260  |  
261  |  partition(...)
262  |      S.partition(sep) -> (head, sep, tail)
263  |      
264  |      Search for the separator sep in S, and return the part before it,
265  |      the separator itself, and the part after it.  If the separator is not
266  |      found, return S and two empty strings.
267  |  
268  |  replace(...)
269  |      S.replace(old, new[, count]) -> str
270  |      
271  |      Return a copy of S with all occurrences of substring
272  |      old replaced by new.  If the optional argument count is
273  |      given, only the first count occurrences are replaced.
274  |  
275  |  rfind(...)
276  |      S.rfind(sub[, start[, end]]) -> int
277  |      
278  |      Return the highest index in S where substring sub is found,
279  |      such that sub is contained within S[start:end].  Optional
280  |      arguments start and end are interpreted as in slice notation.
281  |      
282  |      Return -1 on failure.
283  |  
284  |  rindex(...)
285  |      S.rindex(sub[, start[, end]]) -> int
286  |      
287  |      Return the highest index in S where substring sub is found,
288  |      such that sub is contained within S[start:end].  Optional
289  |      arguments start and end are interpreted as in slice notation.
290  |      
291  |      Raises ValueError when the substring is not found.
292  |  
293  |  rjust(...)
294  |      S.rjust(width[, fillchar]) -> str
295  |      
296  |      Return S right-justified in a string of length width. Padding is
297  |      done using the specified fill character (default is a space).
298  |  
299  |  rpartition(...)
300  |      S.rpartition(sep) -> (head, sep, tail)
301  |      
302  |      Search for the separator sep in S, starting at the end of S, and return
303  |      the part before it, the separator itself, and the part after it.  If the
304  |      separator is not found, return two empty strings and S.
305  |  
306  |  rsplit(...)
307  |      S.rsplit(sep=None, maxsplit=-1) -> list of strings
308  |      
309  |      Return a list of the words in S, using sep as the
310  |      delimiter string, starting at the end of the string and
311  |      working to the front.  If maxsplit is given, at most maxsplit
312  |      splits are done. If sep is not specified, any whitespace string
313  |      is a separator.
314  |  
315  |  rstrip(...)
316  |      S.rstrip([chars]) -> str
317  |      
318  |      Return a copy of the string S with trailing whitespace removed.
319  |      If chars is given and not None, remove characters in chars instead.
320  |  
321  |  split(...)
322  |      S.split(sep=None, maxsplit=-1) -> list of strings
323  |      
324  |      Return a list of the words in S, using sep as the
325  |      delimiter string.  If maxsplit is given, at most maxsplit
326  |      splits are done. If sep is not specified or is None, any
327  |      whitespace string is a separator and empty strings are
328  |      removed from the result.
329  |  
330  |  splitlines(...)
331  |      S.splitlines([keepends]) -> list of strings
332  |      
333  |      Return a list of the lines in S, breaking at line boundaries.
334  |      Line breaks are not included in the resulting list unless keepends
335  |      is given and true.
336  |  
337  |  startswith(...)
338  |      S.startswith(prefix[, start[, end]]) -> bool
339  |      
340  |      Return True if S starts with the specified prefix, False otherwise.
341  |      With optional start, test S beginning at that position.
342  |      With optional end, stop comparing S at that position.
343  |      prefix can also be a tuple of strings to try.
344  |  
345  |  strip(...)
346  |      S.strip([chars]) -> str
347  |      
348  |      Return a copy of the string S with leading and trailing
349  |      whitespace removed.
350  |      If chars is given and not None, remove characters in chars instead.
351  |  
352  |  swapcase(...)
353  |      S.swapcase() -> str
354  |      
355  |      Return a copy of S with uppercase characters converted to lowercase
356  |      and vice versa.
357  |  
358  |  title(...)
359  |      S.title() -> str
360  |      
361  |      Return a titlecased version of S, i.e. words start with title case
362  |      characters, all remaining cased characters have lower case.
363  |  
364  |  translate(...)
365  |      S.translate(table) -> str
366  |      
367  |      Return a copy of the string S in which each character has been mapped
368  |      through the given translation table. The table must implement
369  |      lookup/indexing via __getitem__, for instance a dictionary or list,
370  |      mapping Unicode ordinals to Unicode ordinals, strings, or None. If
371  |      this operation raises LookupError, the character is left untouched.
372  |      Characters mapped to None are deleted.
373  |  
374  |  upper(...)
375  |      S.upper() -> str
376  |      
377  |      Return a copy of S converted to uppercase.
378  |  
379  |  zfill(...)
380  |      S.zfill(width) -> str
381  |      
382  |      Pad a numeric string S with zeros on the left, to fill a field
383  |      of the specified width. The string S is never truncated.
384  |  
385  |  ----------------------------------------------------------------------
386  |  Static methods defined here:
387  |  
388  |  maketrans(x, y=None, z=None, /)
389  |      Return a translation table usable for str.translate().
390  |      
391  |      If there is only one argument, it must be a dictionary mapping Unicode
392  |      ordinals (integers) or characters to Unicode ordinals, strings or None.
393  |      Character keys will be then converted to ordinals.
394  |      If there are two arguments, they must be strings of equal length, and
395  |      in the resulting dictionary, each character in x will be mapped to the
396  |      character at the same position in y. If there is a third argument, it
397  |      must be a string, whose characters will be mapped to None in the result.
help用法

在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出

或者直接执行help(o),o是参数,查看和变量o有关的操作。。。

和调用相关

callable(s),s是参数,看这个变量是不是可调用。

如果s是一个函数名,就会返回True

1 def func():pass
2 print(callable(func))#True
3 print(callable(123))#Flase
callable实例

查看参数所属类型的所有内置方法

dir() 默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量

1 dir(list)
2 
3 
4 
5 
6 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
dir实例

和数字相关

 

 

 

数字——数据类型相关:bool,int,float,complex

数字——进制转换相关:bin,oct,hex

数字——数学运算:abs,divmod,min,max,sum,round,pow

和数据结构相关

 

 

 

序列——列表和元组相关的:list和tuple

序列——字符串相关的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

1 ret=bytearray('xiaozhangmen',encoding='utf-8')
2 print(ret)#bytearray(b'xiaozhangmen')
bytearray
1 ret = memoryview(bytes('你好',encoding='utf-8'))
2 print(len(ret))
3 print(bytes(ret[:3]).decode('utf-8'))
4 print(bytes(ret[3:]).decode('utf-8'))
memoryview

序列:reversed,slice

1 l=[1,2,3,4,5,6]
2 l.reverse()
3 print(l)#[6, 5, 4, 3, 2, 1]
reverse
1 l=[1,2,3,4,5,6]
2 sli=slice(1,4,2)#slice看起来返回的是一个规则,拿到这个规则后再对列表进行操作
3 print(l[sli])#[2, 4]
slice

数据集合——字典和集合:dict,set,frozenset

数据集合:len,sorted,enumerate,all,any,zip,filter,map

filter:使用指定方法过滤可迭代对象的元素

1 def is_odd(x):
2     return x % 2 == 1
3 print(filter(is_odd,[1,2,3,4,5,6]))#<filter object at 0x00000000022EC240>
4 print(list(filter(is_odd,[1,2,3,4,5,6])))#[1, 3, 5]
filter

map:python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

1 def pow(x):
2     return x**2
3 print(map(pow,[0,1,2,3]))#<map object at 0x000000000291C1D0>
4 print(list(map(pow,[0,1,2,3])))#[0, 1, 4, 9]
map

匿名函数

匿名函数:为了解决那些功能很简单的需求而设计的一句话函数

匿名函数格式:

函数名 = lambda 参数 :返回值

#参数可以有多个,用逗号隔开
#匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
#返回值和正常的函数一样可以是任意数据类型

 匿名函数实例

1 #如把下面函数改为匿名函数
2 def add(x,y):
3     return x+y
4 
5 add1=lambda x,y:x+y
6 
7 print(add(1,2))
8 print(add1(1,2))

 

 

 

 

 

 

 

 

 

 

 

 

 

面试题笔记:

现有两个元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

1 #答案一
2 test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
3 print(test(t1,t2))
4 #答案二
5 print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))
6 #还可以这样写
7 print([{i:j} for i,j in zip(t1,t2)])
Code
 1 1.下面程序的输出结果是:
 2 d = lambda p:p*2
 3 t = lambda p:p*3
 4 x = 2
 5 x = d(x)
 6 x = t(x)
 7 x = d(x)
 8 print x
 9 
10 2.现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
11 
12 3.以下代码的输出是什么?请给出答案并解释。
13 def multipliers():
14     return [lambda x:i*x for i in range(4)]
15 print([m(2) for m in multipliers()])
16 请修改multipliers的定义来产生期望的结果。
习题