__author__ = '孟强' # 1.abs(x) 返回数字(可为普通型、长整型或浮点型)的绝对值。如果给出复数,返回值就是该复数的模 ''' print("abs()") a = [abs(2.0), abs(-2), abs(-3j+4)] print(a) ''' # 2. apply(function,args[,keywords]) 3.4.3不存在 # apply()函数将args参数应用到function上。function参数必须是可调用对象(函数、方法或其他可调用对象)。 # args参数必须以序列形式给出。列表在应用之前被转换为元组。function对象在被调用时,将args列表的内容分别作为独立的参数看待。 ''' def sumall(*args): a = 0 for i in args: a += i return a a = apply(sumall, (1, 2, 3, 4)) print(a) ''' # 2 all(iterable) # Return True if all elements of the iterable are true (or if the iterable is empty). # Equivalent to: ''' def all(iterable): for element in iterable: if not element: return False return True ''' # any(iterable) # Return True if any element of the iterable is true. If the iterable is empty, return False. # Equivalent to: ''' def any(iterable): for element in iterable: if element: return True return False ''' # ascii(object) 将字符转化成ascii码,若是遇到非ascii字符就会以x u U(unicode)代替 # As repr(), return a string containing a printable representation of an object, # but escape the non-ASCII characters in the string returned by repr() using x, u or U escapes. # This generates a string similar to that returned by repr() in Python 2. ''' a = '中国' b = ascii(a) print(b) ''' # bin(x) 将一个整数转化成二进制 二进制前面有'-'时表示负数 用浮点数作参数会报错 # Convert an integer number to a binary string. The result is a valid Python expression. # If x is not a Python int object, it has to define an __index__() method that returns an integer. # ''' a = 8989979864548778 print(bin(a)) a = -4564654 print(bin(a)) ''' # 分辨True orFalse ''' Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false: None False zero of any numeric type, for example, 0, 0.0, 0j. any empty sequence, for example, '', (), []. any empty mapping, for example, {}. instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False. [1] All other values are considered true — so objects of many types are always true. ''' # class bool([x]) 返回x是True 或者 False 如果不填x则是False # Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. # If x is false or omitted, this returns False; otherwise it returns True. # The bool class is a subclass of int (see Numeric Types — int, float, complex). # It cannot be subclassed further. Its only instances are False and True (see Boolean Values). ''' print(bool()) # omitted -> False print(bool(0)) # False print(bool([(), ])) # True print(bool((()))) # False 外面的小括号在被解析时不会被当作tuple,而会当作括号 print(bool(((),))) # True print(bool(((), ()))) # True print(bool(([]))) # False print(bool(([], []))) # True ''' # class bytearray([source[, encoding[, errors]]]) 返回byte数组,bytearray是可以被修改的 范围[0,256] # Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. # It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, # as well as most methods that the bytes type has, see Bytes and Bytearray Operations. # Without an argument, an array of size 0 is created. 没有参数时,一个大小为0的数组将会被创建 ''' a = '中国' a = bytearray(a, 'utf-8') print(a) # bytearray(b'xe4xb8xadxe5x9bxbd') ''' # class bytes([source[, encoding[, errors]]]) bytes类型是不可修改的,范围[0,256] # Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. # bytes is an immutable version of bytearray – it has the same non-mutating methods # and the same indexing and slicing behavior. ''' a = bytes('中国', 'utf-8') print(a) # b'xe4xb8xadxe5x9bxbd' ''' # callable(object) # Return True if the object argument appears callable, False if not. If this returns true, # it is still possible that a call fails, but if it is false, calling object will never succeed. # Note that classes are callable (calling a class returns a new instance); # instances are callable if their class has a __call__() method. # 如果实例有_call()_方法,那么该object是可调用的 否则返回值为False # ''' def add(a, b): # 方法是callable的 return a + b class A(): # 类的实例必须要有__call__方法才是可调用的,而类是可调用的 def haha(self): print("haha") pass pass class B: def __call__(self): return 0 a = [callable(0), callable("mystring"), callable(add), callable(A), callable(A()), callable(B), callable(B())] # False False True True False True True print(a) ''' # chr(i)¶ 最多支持0到0x10FFFF的数 # Return the string representing a character whose Unicode code point is the integer i. # For example, chr(97) returns the string 'a'. This is the inverse of ord(). # The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). # ValueError will be raised if i is outside that range. ''' a = [chr(97), chr(321312), chr(0), chr(0x10FFFF)] # 'a' , 'U0004e720','x00','U0010ffff'' print(a) ''' # classmethod(function) 为函数返回一个类方法 # Return a class method for function. ''' class C: @classmethod def f(cls, arg1, arg2, ...): ... ''' # compile(source, filename, mode[, flags[, dont_inherit]]) # 中文说明:将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。 # AST 抽象语法树 # 参数source:字符串或者AST(Abstract Syntax Trees)对象。 # 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。 # 参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。 # 参数flag和dont_inherit:这两个参数暂不介绍,可选参数。 ''' >>> code = "for i in range(0, 10): print i" >>> cmpcode = compile(code, '', 'exec') >>> exec cmpcode 0 1 2 3 4 5 6 7 8 9 >>> str = "3 * 4 + 5" >>> a = compile(str,'','eval') >>> eval(a) 17 ''' # complex([real[, imag]]) # 中文说明: # 创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。imag默认为0 # 参数real: int, long, float或字符串; # 参数imag: int, long, float。 ''' a = complex(3) print(a) a = complex("3") print(a) a = complex("3j") print(a) # a = complex("1+1+2j") # 报错 # a = complex("1 + 2j") # 报错 不能有空格 a = complex("1+2j") # ok print(a) ''' # delattr(object, name) 移除对象object的属性 # This is a relative of setattr(). The arguments are an object and a string. # The string must be the name of one of the object’s attributes. # The function deletes the named attribute, provided the object allows it. # For example, delattr(x, 'foobar') is equivalent to del x.foobar. # class dict(**kwarg) # class dict(mapping, **kwarg) # class dict(iterable, **kwarg) # Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class. # For other containers see the built-in list, set, and tuple classes, as well as the collections module. ''' a = (1,2,3,4,5) b = [6,7,8,9,10] print(dict(zip(a,b))) print(dict(a=1, b=2, c=3)) d3 = dict([('one', 1), ('two', 2), ('three', 3)]) print(d3) ''' # dir([object]) # Without arguments, return the list of names in the current local scope. # 没有参数则会打印当前局部作用域下的属性列表 # With an argument, attempt to return a list of valid attributes for that object. # 如果有参数,则尝试返回该对象的合法属性列表 # If the object has a method named __dir__(), this method will be called and must return the list of attributes. ''' class Shape: def __dir__(self): return ['area', 'perimeter', 'location'] class A(): b = 1 c = 1 a = A() b = Shape() print(dir()) print(dir(A)) print(dir(Shape)) print(dir(b)) ''' # divmod(a, b) 两个整数或者浮点数相除,返回商及余数 # Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder # when using integer division. # 原理:c,d = divmod(a,b)中 c = max.floor(a/b) d则为余数 ''' a, b = divmod(5, 2) # a:2 b:1 print(a) print(b) a, b = divmod(5.4, 2) # a:2.0 b:1.4000000000000004 print(a) print(b) c, d = divmod(-3, 2) print(c, d) # -2 1 ''' # enumerate(iterable, start=0) # Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. # The __next__() method of the iterator returned by enumerate() returns a tuple containing a count # (from start which defaults to 0) and the values obtained from iterating over iterable. # enumerate方法等价于下面的函数,因而只会查找一遍值 ''' def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 ''' ''' def main(): a = enumerate((1, 2, 3, 4, 5, 6)) for m in a: print(m) # (0,1) (1,2) ... print(type(m)) # tuple for m in a: print(m) # (0,1) (1,2) ... print(type(m)) # tuple b = list(a) print(type(b)) for i in b: print(i) # (0,1) (1,2) ... print(type(i)) # tuple print(type(a)) if __name__ == "__main__": main() ''' # eval(expression, globals=None, locals=None) 执行一个表达式,或字符串作为运算 # The arguments are a string and optional globals and locals. # If provided, globals must be a dictionary. ''' x = 1 print(eval('x+1')) ''' # exec:支持python代码的动态执行,执行存储在字符串或者文件中的Python语句 # python3 中没有reduce函数 # filter(function, iterable) 见有道云笔记map filter reduce # map(function, iterable) # 将参数传至function里面处理,并且返回的是一个可迭代类型 ''' a = map(lambda x: x**2, [1, 2, 3, 4, 5, 6, 7]) # 返回的是一个可迭代类型 print(type(a)) for i in a: print(i) # fileter(function, iterable)filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。 a = filter(lambda x: x % 2, [1, 2, 3, 4, 5, 6]) print(type(a)) for i in a: print(i) a = bytes("hello", 'utf8') print(a) print(type(a)) l = [i for i in range(10) if i % 2 == 0] print(l) 列表推倒式 ''' # class float([x]) # 语法如下 ''' sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" numeric_value ::= floatnumber | infinity | nan numeric_string ::= [sign] numeric_value # 示例如下 >>> float('+1.23') 1.23 >>> float('-12345 ') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf ''' # class frozenset([iterable]) frozenset是集合类型,但是集合类型中set可变 而frozenset不可变 # Return a new frozenset object, optionally with elements taken from iterable # Python中的set不支持indexing,但支持len(set),x in set 等操作。 ''' a = frozenset((1,2,3,4,5)) print(a) ''' # class set([iterable]) # Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class. # getattr(object, name[, default]) 用于返回对象的某个属性,name为string,如果属性不存在,则异常抛出 # Return the value of the named attribute of object. name must be a string. # If the string is the name of one of the object’s attributes, the result is the value of that attribute. # For example, getattr(x, 'foobar') is equivalent to x.foobar. # If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. # setattr(object, name, value) # hasattr(object, name) # The arguments are an object and a string. # The result is True if the string is the name of one of the object’s attributes, False if not. # globals() # Return a dictionary representing the current global symbol table. # This is always the dictionary of the current module (inside a function or method, # this is the module where it is defined, not the module from which it is called). # locals() # Update and return a dictionary representing the current local symbol table. # Free variables are returned by locals() when it is called in function blocks, but not in class blocks. # ord:得到一个字符串或unicode类型的ascii数值 # Given a string representing one Unicode character, return an integer representing the Unicode code point # of that character. For example, ord('a') returns the integer 97 and ord('u2020') returns 8224. # This is the inverse of chr(). ''' print(ord('a')) print(ord('中')) ''' # pow(x, y[, z]) x**y 如果有z存在,则返回x**y%z # Return x to the power y; if z is present, return x to the power y, modulo z # (computed more efficiently than pow(x, y) % z). # The two-argument form pow(x, y) is equivalent to using the power operator: x**y. ''' a = [pow(3, 2), pow(3, 2, 5)] print(a) ''' # class property(fget=None, fset=None, fdel=None, doc=None) # Return a property attribute. # fget is a function for getting an attribute value. # fset is a function for setting an attribute value. # fdel is a function for deleting an attribute value. # And doc creates a docstring for the attribute. # A typical use is to define a managed attribute x: #If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter. # If given, doc will be the docstring of the property attribute. # Otherwise, the property will copy fget‘s docstring (if it exists). # This makes it possible to create read-only properties easily using property() as a decorator: ''' class C: def __init__(self): self._x = None def getx(self): print("getx") return self._x def setx(self, value): print("setx") self._x = value def delx(self): print("delx") del self._x # 删除属性的方法 x = property(getx, setx, delx, "I'm the 'x' property.") c = C() print(c.x) # 打印“getx” 再打印None c.x = 3 # 打印"setx" print(c.x) # 打印“getx” 再打印3 c.delx() # 打印 "delx" print(repr(a)) ''' # reversed(seq) # Return a reverse iterator. seq must be an object which has a __reversed__() method # or supports the sequence protocol (the __len__() method and the __getitem__() method # with integer arguments starting at 0). ''' a = [1, 2, 3, 4, 5] b = (1, 2, 3, 4, 5) c = "12345" print(list(reversed(a))) # reversed之后是一个reversed迭代器,可通过list变成列表 print(list(reversed(b))) print(list(reversed(c))) print(a[::-1]) # 我认为这种方法很好 print(b[::-1]) print(c[::-1]) print(repr(a)) ''' # round(number[, ndigits]) 返回四舍五入的浮点数,ndigits是精度 # Return the floating point value number rounded to ndigits digits after the decimal point. # If ndigits is omitted, it defaults to zero. Delegates to number.__round__(ndigits). ''' a = 123.4567890 b = [round(a)] + [(i, round(a, i)) for i in range(10)] # round(a,0)和round(a)不同 只有一个参数时,将返回整数 print(b) ''' # sorted(iterable[, key][, reverse]) 读取一个可迭代的类型,返回一个新的列表 # Return a new sorted list from the items in iterable. ''' a = sorted((1, 2, 3, 4, 5)) # 元组类型可以 print(a) a = sorted("1234567") print(a) # 返回列表 a = sorted([1,2,3,4,5], reverse=True) # 从大到小 print(a) # ''' # vars([object]) # Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. # zip(*iterables) # Make an iterator that aggregates elements from each of the iterables. # Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to: ''' a = [1,2,3,4] b = "1234" c= zip(a,b) # 元组迭代器 for i in c: print(i) a = {'a':1, 'b':2, 'c':3, 'd':4} print(a) a = dict(zip(a.values(),a.keys())) print(a) a = ((1,2),(3,4),(5,6),(5,6)) # 会去重 print(dict(a)) a = (1,2,3,4,5,6,7,8) # 转化成字典会出错 a = [1,2,3,4,5,6,7,8] # 转化成字典会出错 a =([1,2],[3,4]) # 转化成字典成功 print(dict(a)) ''' a = {1: 2, 2: 3} print(a)