六、Python-python基础(一)-- 内置函数
一、lambda 表达式
可以将简单的函数表示为lambda表达式
def fun1(a,b): #普通函数 return a > b t = lambda a,b: a > b #lambda表达式 print(t(1,2)) #调用lambda表达式
二、内置函数
1 18 # functions 19 20 def abs(*args, **kwargs): # real signature unknown 21 """ 返回数据的绝对值t. """ 22 pass 23 24 def all(*args, **kwargs): # real signature unknown 25 """ 如果集合的每个元素都是真,则返回真 26 Return True if bool(x) is True for all values x in the iterable. 27 28 If the iterable is empty, return True. 29 """ 30 pass 31 32 def any(*args, **kwargs): # real signature unknown 33 """ 如果集合的一个元素为真,则返回真。如果是空集合,返回False 34 Return True if bool(x) is True for any x in the iterable. 35 36 If the iterable is empty, return False. 37 """ 38 pass 39 40 def ascii(*args, **kwargs): # real signature unknown 41 """ 去对象的类中查找_repr_,获得它的返回值 42 Return an ASCII-only representation of an object. 43 44 As repr(), return a string containing a printable representation of an 45 object, but escape the non-ASCII characters in the string returned by 46 repr() using \\x, \\u or \\U escapes. This generates a string similar 47 to that returned by repr() in Python 2. 48 """ 49 pass 50 51 def bin(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 52 """ 将数值转换为2进制 53 Return the binary representation of an integer. 54 55 >>> bin(2796202) 56 '0b1010101010101010101010' 57 """ 58 pass 59 60 def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__ 61 """ 判断函数是可调用的 62 Return whether the object is callable (i.e., some kind of function). 63 64 Note that classes are callable, as are instances of classes with a 65 __call__() method. 66 """ 67 pass 68 69 def chr(*args, **kwargs): # real signature unknown 70 """ 返回一个数值对应的 ASCII 对应的字符。 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """ 71 pass 72 90 112 def dir(p_object=None): # real signature unknown; restored from __doc__ 113 """ 返回一个对象,内部可以使用的方法
li = []
print(dir(li))
114 dir([object]) -> list of strings 115 116 If called without an argument, return the names in the current scope. 117 Else, return an alphabetized list of names comprising (some of) the attributes 118 of the given object, and of attributes reachable from it. 119 If the object supplies a method named __dir__, it will be used; otherwise 120 the default dir() logic is used and returns: 121 for a module object: the module's attributes. 122 for a class object: its attributes, and recursively the attributes 123 of its bases. 124 for any other object: its attributes, its class's attributes, and 125 recursively the attributes of its class's base classes. 126 """ 127 return [] 128 129 def divmod(x, y): # known case of builtins.divmod 130 """ 求一个除的 商和余数
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x. """ 131 return (0, 0) 132 133 def eval(*args, **kwargs): # real signature unknown 134 """ 得到字符串中的表达式结果
135 Evaluate the given source in the context of globals and locals. 136 137 The source may be a string representing a Python expression 138 or a code object as returned by compile(). 139 The globals must be a dictionary and locals can be any mapping, 140 defaulting to the current globals and locals. 141 If only globals is given, locals defaults to it. 142 """ 143 pass 144 145 def exec(*args, **kwargs): # real signature unknown 146 """ 执行 字符串 中的命令
exec('print(2) if 1 >2 else print(1)')
147 Execute the given source in the context of globals and locals. 148 149 The source may be a string representing one or more Python statements 150 or a code object as returned by compile(). 151 The globals must be a dictionary and locals can be any mapping, 152 defaulting to the current globals and locals. 153 If only globals is given, locals defaults to it. 154 """ 155 pass 156 157 def exit(*args, **kwargs): # real signature unknown 158 pass 159 160 def format(*args, **kwargs): # real signature unknown 161 """ 数据格式化
a = 'i am {0}, {1}'
print(a.format('yan',10))
162 Return value.__format__(format_spec) 163 164 format_spec defaults to the empty string 165 """ 166 pass 167 177 178 def globals(*args, **kwargs): # real signature unknown 179 """ 获取当前的所有全局变量 180 Return the dictionary containing the current scope's global variables. 181 182 NOTE: Updates to this dictionary *will* affect name lookups in the current 183 global scope and vice-versa. 184 """ 185 pass 186 187 204 def help(): # real signature unknown; restored from __doc__ 205 """ 获取一个了 对象 的详细介绍 206 Define the builtin 'help'. 207 208 This is a wrapper around pydoc.help that provides a helpful message 209 when 'help' is typed at the Python interactive prompt. 210 211 Calling help() at the Python prompt starts an interactive help session. 212 Calling help(thing) prints help for the python object 'thing'. 213 """ 214 pass 215 216 def hex(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 217 """ 十进制转换十六进制 218 Return the hexadecimal representation of an integer. 219 220 >>> hex(12648430) 221 '0xc0ffee' 222 """ 223 pass 224 225 def id(*args, **kwargs): # real signature unknown 226 """ 获取一个对应的内存地址 227 Return the identity of an object. 228 229 This is guaranteed to be unique among simultaneously existing objects. 230 (CPython uses the object's memory address.) 231 """ 232 pass 233 234 def input(*args, **kwargs): # real signature unknown 235 """ 获取用户的键盘输入 236 Read a string from standard input. The trailing newline is stripped. 237 238 The prompt string, if given, is printed to standard output without a 239 trailing newline before reading input. 240 241 If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. 242 On *nix systems, readline is used if available. 243 """ 244 pass 245 246 def isinstance(x, A_tuple): # real signature unknown; restored from __doc__ 247 """ 判断对象的类型
a = [11]
print(isinstance(a,list))
248 Return whether an object is an instance of a class or of a subclass thereof. 249 250 A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to 251 check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) 252 or ...`` etc. 253 """ 254 pass 255 256 def issubclass(x, A_tuple): # real signature unknown; restored from __doc__ 257 """ 判断 是不是X的子类。 258 Return whether 'cls' is a derived from another class or is the same class. 259 260 A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to 261 check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) 262 or ...`` etc. 263 """ 264 pass 265 266 def iter(source, sentinel=None): # known special case of iter 267 """ 将一个可迭代对象,通过next()来获取下一个值 268 iter(iterable) -> iterator 269 iter(callable, sentinel) -> iterator 270 271 Get an iterator from an object. In the first form, the argument must 272 supply its own iterator, or be a sequence. 273 In the second form, the callable is called until it returns the sentinel. 274 """ 275 pass 276 277 def len(*args, **kwargs): # real signature unknown 278 """获得一个集合的长度 Return the number of items in a container. """ 279 pass 280 281 def license(*args, **kwargs): # real signature unknown 282 """ 283 interactive prompt objects for printing the license text, a list of 284 contributors and the copyright notice. 285 """ 286 pass 287 288 def locals(*args, **kwargs): # real signature unknown 289 """ 获得当前作用域的局部变量 290 Return a dictionary containing the current scope's local variables. 291 292 NOTE: Whether or not updates to this dictionary will affect name lookups in 293 the local scope and vice-versa is *implementation dependent* and not 294 covered by any backwards compatibility guarantees. 295 """ 296 pass 297 298 def max(*args, key=None): # known special case of max 299 """ 获得最大值 300 max(iterable, *[, default=obj, key=func]) -> value 301 max(arg1, arg2, *args, *[, key=func]) -> value 302 303 With a single iterable argument, return its biggest item. The 304 default keyword-only argument specifies an object to return if 305 the provided iterable is empty. 306 With two or more arguments, return the largest argument. 307 """ 308 pass 309 310 def min(*args, key=None): # known special case of min 311 """ 获得最小值 312 min(iterable, *[, default=obj, key=func]) -> value 313 min(arg1, arg2, *args, *[, key=func]) -> value 314 315 With a single iterable argument, return its smallest item. The 316 default keyword-only argument specifies an object to return if 317 the provided iterable is empty. 318 With two or more arguments, return the smallest argument. 319 """ 320 pass 321 322 def next(iterator, default=None): # real signature unknown; restored from __doc__ 323 """与iter 一起使用。 iter 创建可迭代对象。 使用next 每次得到一个数据
a = iter([11,22,33,44])
print(next(a))
print(next(a))
324 next(iterator[, default]) 325 326 Return the next item from the iterator. If default is given and the iterator 327 is exhausted, it is returned instead of raising StopIteration. 328 """ 329 pass 330 331 def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 332 """ 十进制转换八进制 333 Return the octal representation of an integer. 334 335 >>> oct(342391) 336 '0o1234567' 337 """ 338 pass 339 340 def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open 341 """ 打开文件操作 342 Open file and return a stream. Raise IOError upon failure. 343 461 pass 462 463 def ord(*args, **kwargs): # real signature unknown 464 """ 获取一个字符的的ASCII数值 Return the Unicode code point for a one-character string. """ 465 pass 466 467 def pow(*args, **kwargs): # real signature unknown 468 """获得一个数据的的指数 469 Equivalent to x**y (with two arguments) or x**y % z (with three arguments) 470 471 Some types, such as ints, are able to use a more efficient algorithm when 472 invoked using the three argument form. 473 """ 474 pass 475 476 def print(self, *args, sep=' ', end='\n', file=None): # known special case of print 477 """ 打印 478 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 479 480 Prints the values to a stream, or to sys.stdout by default. 481 Optional keyword arguments: 482 file: a file-like object (stream); defaults to the current sys.stdout. 483 sep: string inserted between values, default a space. 484 end: string appended after the last value, default a newline. 485 flush: whether to forcibly flush the stream. 486 """ 487 pass 488 48 492 def repr(obj): # real signature unknown; restored from __doc__ 493 """ 494 Return the canonical string representation of the object. 495 496 For many object types, including most builtins, eval(repr(obj)) == obj. 497 """ 498 pass 499 500 def round(number, ndigits=None): # real signature unknown; restored from __doc__ 501 """ 数据四舍五入 502 round(number[, ndigits]) -> number 503 504 Round a number to a given precision in decimal digits (default 0 digits). 505 This returns an int when called with one argument, otherwise the 506 same type as the number. ndigits may be negative. 507 """ 508 return 0 509 517 518 def sorted(*args, **kwargs): # real signature unknown 519 """ 排序 520 Return a new list containing all items from the iterable in ascending order. 521 522 A custom key function can be supplied to customise the sort order, and the 523 reverse flag can be set to request the result in descending order. 524 """ 525 pass 526 527 def sum(*args, **kwargs): # real signature unknown 528 """ 数值求和 529 Return the sum of a 'start' value (default: 0) plus an iterable of numbers 530 531 When the iterable is empty, return the start value. 532 This function is intended specifically for use with numeric values and may 533 reject non-numeric types. 534 """ 535 pass 536 592 def close(self): 593 '''关闭文件 Raises new GeneratorExit exception inside the generator to terminate the iteration.''' 594 pass 595 2704
三、进制转换
bin() :十进制转换二进制
oct():十进制转换八进制
int():十进制转换十进制
hex():十进制转换十六进制
如果将其他进制转换为十进制
1 print(int('0b110',base = 2)) 2 print(int('0o110',base = 8)) 3 print(int('0x11',base = 16))
四、内置函数的排序
实现字符串的排序, 按照首字母排序。 顺序:字符串包含 数值、包含大写、包含小写、包含中文
1 a = ['11','22','abc','ABC', 'db','中文'] 2 li = sorted(a) 3 4 for item in li: 5 print(item) 6 7 8 C:\Python35\python.exe D:/python/decode.py 9 11 10 22 11 ABC 12 abc 13 db 14 中文
五、随机验证码
主要思路,使用random.randrange()来生成随机的数值。 使用char()将数值转换为字符。
import random temp = '' for i in range(6): a = random.randrange(0,4) if a==2 or a ==4: rad1 = random.randrange(65,91) c1 = chr(rad1) temp = temp + c1 else: rad2 = random.randrange(0,9) c1 = str(rad2) temp = temp + c1 print(temp)

浙公网安备 33010602011771号