Python入门知识拾遗
1.标识符
1 字母数字下划线组成,不能以数字开头
2.关键字
1 系统定义的标识符我们不能再次定义
1 In [3]: help('keywords') 2 3 Here is a list of the Python keywords. Enter any keyword to get more help. 4 5 False def if raise 6 None del import return 7 True elif in try 8 and else is while 9 as except lambda with 10 assert finally nonlocal yield 11 break for not 12 class from or 13 continue global pass
注:其他常见帮助函数
查看python所有的modules:help("modules") 单看python所有的modules中包含指定字符串的modules: help("modules yourstr") 查看python中常见的topics: help("topics") 查看python标准库中的module:import os.path + help("os.path") 查看python内置的类型:help("list") 查看python类型的成员方法:help("str.find") 查看python内置函数:help("open")
3.作用域
在之前学习变量的作用域时,经常会提到局部变量和全局变量,之所有称之为局部、全局,就是因为他们的自作用的区域不同,这就是作用域
(1)Python无块级作用域
所谓块集作用域,需要先了解Python的代码块概念。Python遵从严格的缩进标准,可以认为处在同一缩进之间的代码即为一个代码块。如if判断,for,while循环等。
(2)Python以函数为作用域
Python语法中,函数体为单独的作用域。就行在运行代码时,遇到函数默认是不执行函数体里面的代码的,等待调用函数后才会执行。因此,函数内定义的变量只能在函数内调用。
1 #作用域链 2 3 name = "lzl" 4 def f1(): 5 name = "Eric" 6 def f2(): 7 name = "Snor" 8 print(name) 9 f2() 10 f1()
局部变量:函数里面定义的变量,只能在函数里面访问到,当超出其作用域时,将失去其作用
全局变量:函数外部定义的变量,无论在任何作用域都可以使用。当前作用域有相同变量名的局部变量时,局部变量生效。
全部变量定义的位置:函数定义之外,函数调用之前
(3)全局变量和局部变量名字相同时
1 当局部变量和全局变量名字相同时,默认对局部变量进行修改,若要对全局变量修改,需要声明global
1 ''' 2 def get_wendu(): 3 wendu = 33 4 return wendu 5 6 def print_wendu(wendu): 7 print("温度是%d"%wendu) 8 9 result = get_wendu() #如果一个函数有返回值,但是没有在调用函数之前 用个变量保存的话,那么没有任何意义 10 print_wendu(result) 11 ''' 12 13 #定义一个全局变量,wendu 14 wendu = 0 15 16 def get_wendu(): 17 #如果wendu这个变量已经在全局变量的位置定义了,此时还想在汉书中对全局变量进行进行修改的话 18 #那么 仅仅是wendu=一个值 这还不够,,此时这个wendu这个变量是一个局部变量,只不过与全局变量名字相同罢了 19 #wendu = 33 20 21 #使用global用来对一个全局变量的声明,那么这个函数中的wendu=33就不是定义一个局部变量, 22 #而是对全局变量进行修改 23 global wendu 24 wendu = 33 25 26 def print_wendu(): 27 print("温度是%d"%wendu) 28 29 get_wendu() 30 print_wendu()
1 a = 100 2 #建议 3 #g_a = 100 4 5 def test(): 6 a = 200#在函数中 如果对一个和全局变量名相同的变量进行=value的时候,默认是定义一个变量 7 #只不过这个变量的名字和全局变量的名字相同罢了 8 # 9 #如果想在执行a=value时,不是定义局部变量,而是对全局变量修改,那么可以添加global进行声明 10 print("a=%d"%a) 11 12 def test1(): 13 print("a=%d"%a)#如果这里打印了100就声明了test函数没有对全局变量修改,而是定义了一个局部变量 14 15 16 test() 17 test1()
1 In [15]: x = [lambda :x for x in range(10)] 2 3 In [16]: x.__class__ 4 Out[16]: list 5 6 In [17]: x[0].__class__ 7 Out[17]: function 8 9 In [18]: x[0]() 10 Out[18]: 9
(4)列表和字典当做全局变量时
字典和列表为全局变量时,在函数内部进行修改时不需要声明global,可以直接修改
(5)命名空间
大约来说,命名空间就是一个容器,其中包含的是映射到不同对象的名称。你可能已经听说过了,Python中的一切——常量,列表,字典,函数,类,等等——都是对象。 这样一种“名称-对象”间的映射,使得我们可以通过为对象指定的名称来访问它。 我们可以把命名空间描述为一个Python字典结构,其中关键词代表名称,而字典值是对象本身(这也是目前Python中命名空间的实现方式),如: a_namespace = {'name_a':object_1, 'name_b':object_2, ...} 现在比较棘手的是,我们在Python中有多个独立的命名空间,而且不同命名空间中的名称可以重复使用(只要对象是独一无二的),比如: a_namespace = {'name_a':object_1, 'name_b':object_2, ...} b_namespace = {'name_a':object_3, 'name_b':object_4, ...} 举例来说,每次我们调用for循环或者定义一个函数的时候,就会创建它自己的命名空间。命名空间也有不同的层次(也就是所谓的“作用域”), 作用域:在上一节中,我们已经学习到命名空间可以相互独立地存在,而且它们被安排在某个特定层次,由此引出了“作用域”的概念。Python中的“作用域”定义了一个“层次”, 我们从其中的命名空间中查找特定的“名称-对象”映射对。 我们已经知道了多个命名空间可以独立存在,而且可以在不同的层次上包含相同的变量名。“作用域”定义了Python在哪一个层次上查找某个“变量名”对应的对象。接下来的问题就是:“Python在查找‘名称-对象’映射时,是按照什么顺序对命名空间的不同层次进行查找的?” 答案就是:使用的是LEGB规则,表示的是Local -> Enclosed -> Global -> Built-in,其中的箭头方向表示的是搜索顺序。 Local 可能是在一个函数或者类方法内部。 Enclosed 可能是嵌套函数内,比如说 一个函数包裹在另一个函数内部。 Global 代表的是执行脚本自身的最高层次。 Built-in 是Python为自身保留的特殊名称。 因此,如果某个name:object映射在局部(local)命名空间中没有找到,接下来就会在闭包作用域(enclosed)进行搜索,如果闭包作用域也没有找到,Python就会到全局(global)命名空间中进行查找,最后会在内建(built-in)命名空间搜索(注:如果一个名称在所有命名空间中都没有找到,就会产生一个NameError)。
4.三元运算
result = value1 if 条件 else value2
如果条件为真:result = value1
如果条件为假:result = value2
5.进制转换
In [25]: a = 10 In [26]: bin(a) Out[26]: '0b1010' In [27]: oct(a) Out[27]: '0o12' In [28]: hex(a) Out[28]: '0xa'
Python基础
所以以下这些值都是对象: "zhangyafei"、23、['太原', '晋城', '北京'],并且是根据不同的类生成的对象。
一、整数(int)
12,23,111
每个整数具有如下功能
class int(object): """ int(x=0) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 """ def bit_length(self): # real signature unknown; restored from __doc__ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any int. """ pass @classmethod # known case def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ int.from_bytes(bytes, byteorder, *, signed=False) -> int Return the integer represented by the given array of bytes. The bytes argument must be a bytes-like object (e.g. bytes or bytearray). The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument indicates whether two's complement is used to represent the integer. """ pass def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ int.to_bytes(length, byteorder, *, signed=False) -> bytes Return an array of bytes representing an integer. The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. """ pass def __abs__(self, *args, **kwargs): # real signature unknown """ abs(self) """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __bool__(self, *args, **kwargs): # real signature unknown """ self != 0 """ pass def __ceil__(self, *args, **kwargs): # real signature unknown """ Ceiling of an Integral returns itself. """ pass def __divmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(self, value). """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __float__(self, *args, **kwargs): # real signature unknown """ float(self) """ pass def __floordiv__(self, *args, **kwargs): # real signature unknown """ Return self//value. """ pass def __floor__(self, *args, **kwargs): # real signature unknown """ Flooring an Integral returns itself. """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __index__(self, *args, **kwargs): # real signature unknown """ Return self converted to an integer, if self is suitable for use as an index into a list. """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ int(x=0) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 # (copied from class doc) """ pass def __int__(self, *args, **kwargs): # real signature unknown """ int(self) """ pass def __invert__(self, *args, **kwargs): # real signature unknown """ ~self """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lshift__(self, *args, **kwargs): # real signature unknown """ Return self<<value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __neg__(self, *args, **kwargs): # real signature unknown """ -self """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __pos__(self, *args, **kwargs): # real signature unknown """ +self """ pass def __pow__(self, *args, **kwargs): # real signature unknown """ Return pow(self, value, mod). """ pass def __radd__(self, *args, **kwargs): # real signature unknown """ Return value+self. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __rdivmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(value, self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rfloordiv__(self, *args, **kwargs): # real signature unknown """ Return value//self. """ pass def __rlshift__(self, *args, **kwargs): # real signature unknown """ Return value<<self. """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return value*self. """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __round__(self, *args, **kwargs): # real signature unknown """ Rounding an Integral returns itself. Rounding with an ndigits argument also returns an integer. """ pass def __rpow__(self, *args, **kwargs): # real signature unknown """ Return pow(value, self, mod). """ pass def __rrshift__(self, *args, **kwargs): # real signature unknown """ Return value>>self. """ pass def __rshift__(self, *args, **kwargs): # real signature unknown """ Return self>>value. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rtruediv__(self, *args, **kwargs): # real signature unknown """ Return value/self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Returns size in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __truediv__(self, *args, **kwargs): # real signature unknown """ Return self/value. """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number"""
二、浮点型(float)
1212.2121,12.32
每个浮点型具有如下功能
class float(object): """ float(x) -> floating point number Convert a string or number to a floating point number, if possible. """ def as_integer_ratio(self): # real signature unknown; restored from __doc__ """ float.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs. >>> (10.0).as_integer_ratio() (10, 1) >>> (0.0).as_integer_ratio() (0, 1) >>> (-.25).as_integer_ratio() (-1, 4) """ pass def conjugate(self, *args, **kwargs): # real signature unknown """ Return self, the complex conjugate of any float. """ pass @staticmethod # known case def fromhex(string): # real signature unknown; restored from __doc__ """ float.fromhex(string) -> float Create a floating-point number from a hexadecimal string. >>> float.fromhex('0x1.ffffp10') 2047.984375 >>> float.fromhex('-0x1p-1074') -5e-324 """ return 0.0 def hex(self): # real signature unknown; restored from __doc__ """ float.hex() -> string Return a hexadecimal representation of a floating-point number. >>> (-0.1).hex() '-0x1.999999999999ap-4' >>> 3.14159.hex() '0x1.921f9f01b866ep+1' """ return "" def is_integer(self, *args, **kwargs): # real signature unknown """ Return True if the float is an integer. """ pass def __abs__(self, *args, **kwargs): # real signature unknown """ abs(self) """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __bool__(self, *args, **kwargs): # real signature unknown """ self != 0 """ pass def __divmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(self, value). """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __float__(self, *args, **kwargs): # real signature unknown """ float(self) """ pass def __floordiv__(self, *args, **kwargs): # real signature unknown """ Return self//value. """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ float.__format__(format_spec) -> string Formats the float according to format_spec. """ return "" def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getformat__(self, typestr): # real signature unknown; restored from __doc__ """ float.__getformat__(typestr) -> string You probably don't want to use this function. It exists mainly to be used in Python's test suite. typestr must be 'double' or 'float'. This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the format of floating point numbers used by the C type named by typestr. """ return "" def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, x): # real signature unknown; restored from __doc__ pass def __int__(self, *args, **kwargs): # real signature unknown """ int(self) """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __neg__(self, *args, **kwargs): # real signature unknown """ -self """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __pos__(self, *args, **kwargs): # real signature unknown """ +self """ pass def __pow__(self, *args, **kwargs): # real signature unknown """ Return pow(self, value, mod). """ pass def __radd__(self, *args, **kwargs): # real signature unknown """ Return value+self. """ pass def __rdivmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(value, self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rfloordiv__(self, *args, **kwargs): # real signature unknown """ Return value//self. """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return value*self. """ pass def __round__(self, *args, **kwargs): # real signature unknown """ Return the Integral closest to x, rounding half toward even. When an argument is passed, work like built-in round(x, ndigits). """ pass def __rpow__(self, *args, **kwargs): # real signature unknown """ Return pow(value, self, mod). """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rtruediv__(self, *args, **kwargs): # real signature unknown """ Return value/self. """ pass def __setformat__(self, typestr, fmt): # real signature unknown; restored from __doc__ """ float.__setformat__(typestr, fmt) -> None You probably don't want to use this function. It exists mainly to be used in Python's test suite. typestr must be 'double' or 'float'. fmt must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be one of the latter two if it appears to match the underlying C reality. Override the automatic determination of C-level floating point type. This affects how floats are converted to and from binary strings. """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __truediv__(self, *args, **kwargs): # real signature unknown """ Return self/value. """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Return the Integral closest to x between 0 and x. """ pass imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number"""
三、字符串(str)
‘zhangyafei','dream’
查找某个字符或子字符串是否在字符串中:str.find(substr)
统计某个字符串在另一个字符串中出现的个数:str.count(substr)
替换:str.replace(str1,str2)
分割:str.split() 默认为空格
去除:str.strip() 把这个字符串头和尾的空格,以及位于头尾的\n \t之类给删 掉。 str.strip(c)
连接:a.join(b) 用a连接起b
每个字符串具有如下功能
class str(object): """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" def casefold(self): # real signature unknown; restored from __doc__ """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ """ S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def format_map(self, mapping): # real signature unknown; restored from __doc__ """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def isidentifier(self): # real signature unknown; restored from __doc__ """ S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isprintable(self): # real signature unknown; restored from __doc__ """ S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def maketrans(self, *args, **kwargs): # real signature unknown """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ pass def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ """ S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return "" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> str Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, *args, **kwargs): # real signature unknown """ Return self[key]. """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass
四、列表(list):往往是相同类型的元素,比如100个数字)
[1,2,3,4,5]
Names=[“张亚飞”,”康越”] 添加新的元素 列表名.append()--------->添加到最后一个 列表名.insert(插入的内容)--------->根据内容添加 列表名.extend(添加的表名)--------->将新表添加到表的末尾 删除元素 列表名.pop()------------->删除最后一个 列表名.remove(删除的内容)---------->根据内容删除 del 列表名[下标]----->根据下标删除 修改 列表名[下标]=new值---->根据下标进行修改 查询 列表名[索引] if 查询的内容 in 列表名:
每个列表具有如下功能
class list(object): """ list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -> None -- append object to end """ pass def clear(self): # real signature unknown; restored from __doc__ """ L.clear() -> None -- remove all items from L """ pass def copy(self): # real signature unknown; restored from __doc__ """ L.copy() -> list -- a shallow copy of L """ return [] def count(self, value): # real signature unknown; restored from __doc__ """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __delitem__(self, *args, **kwargs): # real signature unknown """ Delete self[key]. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iadd__(self, *args, **kwargs): # real signature unknown """ Implement self+=value. """ pass def __imul__(self, *args, **kwargs): # real signature unknown """ Implement self*=value. """ pass def __init__(self, seq=()): # known special case of list.__init__ """ list() -> new empty list list(iterable) -> new list initialized from iterable's items # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None
重要知识点:列表生成式
[exp for iter_var in iterable]
工作过程:
- 迭代iterable中的每个元素;
- 每次迭代都先把结果赋值给iter_var,然后通过exp得到一个新的计算值;
- 最后把所有通过exp得到的计算值以一个新列表的形式返回。
In [6]: lists = [i for i in range(10)] In [7]: lists Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [8]: list(range(10)) Out[8]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
带过滤功能的列表生成式
[exp for iter_var in iterable [if exp]]
In [12]: lists = [i for i in range(10) if i<6] In [13]: lists Out[13]: [0, 1, 2, 3, 4, 5]
循环嵌套语法格式
[exp for iter_var_A in iterable_A for iter_var_B in iterable_B]
L1 = ['香蕉', '苹果', '橙子'] L2 = ['可乐', '牛奶'] # 不使用列表生成式实现 list7 = [] for x in L1: for y in L2: list7.append((x, y)) # 使用列表生成式实现 list8 = [(x, y) for x in L1 for y in L2]
In [16]: list8 Out[16]: [('香蕉', '可乐'), ('香蕉', '牛奶'), ('苹果', '可乐'), ('苹果', '牛奶'), ('橙子', '可乐'), ('橙子', '牛奶')]
列表生成器:即把列表生成式的[]改为(),其内部实现了__next__方法,所以可通过next方法迭代,注意,迭代完之后将取不到值。其设计也是为了节省内存
In [18]: lists = (i for i in range(10)) In [19]: lists Out[19]: <generator object <genexpr> at 0x0000009BD7BC4E08> In [20]: lists.__next__ Out[20]: <method-wrapper '__next__' of generator object at 0x0000009BD7BC4E08> In [21]: lists.__next__() Out[21]: 0 In [22]: next(lists) Out[22]: 1
五、元组(tuple):元组不能增删改,只能查
('zhangyafei','age',23)
元组可以看做内部元素不可改变的列表
查(切片):元组[索引]
元组[start:end:len]
查看某个值在元组出现的个数:元组.count(value1)
示例
# 创建元组 a = tuple(range(10)) a Out[39]: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # 查询某个值的索引 a.index(3) Out[40]: 3 # 查询某个值出现的个数 a.count(5) Out[44]: 1 # 切片 a[1] Out[45]: 1 a[1:4] Out[46]: (1, 2, 3) a[1:4:2] Out[47]: (1, 3) # 增加 a.__add__((10,)) Out[42]: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # 删除 无 # 修改 无
每个元组具有如下功能
class set(object): """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. """ def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. """ pass def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass def discard(self, *args, **kwargs): # real signature unknown """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iand__(self, *args, **kwargs): # real signature unknown """ Return self&=value. """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, *args, **kwargs): # real signature unknown """ Return self|=value. """ pass def __isub__(self, *args, **kwargs): # real signature unknown """ Return self-=value. """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __ixor__(self, *args, **kwargs): # real signature unknown """ Return self^=value. """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass __hash__ = None
六、字典(dict):Python中应用非常广泛的一个数据类型
{‘name’:'zhangyafei','age':23}
字典可以看做键值对
#infor = {键:值,键:值……} #infor = {key:value,key:value} 添加 字典名[新的key] = value 字典A.update(字典B)
删除 del 字典名[key] 无返回值
字典A.pop(key) 有返回值 修改 字典名[已存在的key]=new_value 查询 字典名[key] 字典名.get(key)
字典名.keys()
字典名.values()
字典名.items():items把字典中每一个元素看成一个元组,查看元组值的时候,我们可以根据下标,同时也可以根据相等个数的变量值系统自动赋相应位置上的值
示例
# 添加 a = {} a['k1'] = 'v1' a Out[15]: {'k1': 'v1'} b = {} b['k2'] = 'v2' a.update(b) a Out[19]: {'k1': 'v1', 'k2': 'v2'} # 删除 del a['k1'] a Out[21]: {'k2': 'v2'} # 修改 a['k2'] = 2 a Out[23]: {'k2': 2} # 查询 a.keys() Out[24]: dict_keys(['k2']) a.values() Out[25]: dict_values([2]) a.items() Out[26]: dict_items([('k2', 2)]) a['k2'] Out[27]: 2 a.get('k2') Out[28]: 2 a['k1'] Traceback (most recent call last): File "D:\pytho3.6\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-29-2f084bd92f9b>", line 1, in <module> a['k1'] KeyError: 'k1' a.get('k1')
扩展:对字典排序的几种方法
d = {'a':1,'b':4,'c':2} # 根据键排序 sorted(d.items()) [('a', 1), ('b', 4), ('c', 2)] # 根据value进行排序 # 方式一 sorted(d.items(),key = lambda x:x[1],reverse = True) [('b', 4), ('c', 2), ('a', 1)] sorted(d.items(),key = lambda x:x[1],reverse = False) [('a', 1), ('c', 2), ('b', 4)] # 方法二 import operator sorted(d.items(),key = operator.itemgetter(1)) [('a', 1), ('c', 2), ('b', 4)] # 方法三 sorted(d, key=d.__getitem__) ['a', 'c', 'b'] for k in sorted(d, key=d.__getitem__): print(k, d.get(k)) a 1 c 2 b 4
补充:字典生成式
{key:value for iter_var in iterable}
{i:1 for i in 'hello'}
Out[9]: {'h': 1, 'e': 1, 'l': 1, 'o': 1}
七、集合(set)
{12,23,34,5,6,7}
集合最常用的功能即去重,交并补运算
增:集合.add(元素)
删:集合.pop()
集合.remove()
清空:集合.clear()
求交集:集合1.intersection(集合2)
求并集:集合1.union(集合2)
求补集:集合1.difference(集合2)
每个集合具有如下功能
class set(object): """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. """ def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. """ pass def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass def discard(self, *args, **kwargs): # real signature unknown """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iand__(self, *args, **kwargs): # real signature unknown """ Return self&=value. """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, *args, **kwargs): # real signature unknown """ Return self|=value. """ pass def __isub__(self, *args, **kwargs): # real signature unknown """ Return self-=value. """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __ixor__(self, *args, **kwargs): # real signature unknown """ Return self^=value. """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass __hash__ = None
补充:集合生成式
{exp for iter_var in iterable}
{i for i in 'hello'}
Out[10]: {'e', 'h', 'l', 'o'}
八,collection系列
1.计数器(Counter)
""" Counter Counter是一个简单的计数器,例如,统计字符出现的个数: """ from collections import Counter c = Counter('programming') print(c)
a = Counter({'a':12,'b':43})
# Counter具有字典所有的功能+自己的功能
a = Counter({'name':'zhangyafei','age':23})
a['name']
Out[108]: 'zhangyafei'
2、有序字典(orderedDict )
orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
""" OrderedDict 使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。 如果要保持Key的顺序,可以用OrderedDict: """ from collections import OrderedDict d = dict([('a', 1), ('b', 2), ('c', 3)]) d # dict的Key是无序的 od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) od # OrderedDict的Key是有序的 # 注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
3、默认字典(defaultdict)
""" defaultdict 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict: """ from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' dd['key1'] # key1存在 dd['key2'] # key2不存在,返回默认值
4、可命名元组(namedtuple)
根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。
""" namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。 """ from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) p.x p.y
Circle = namedtuple('Circle', ['x', 'y', 'r'])
5、双向队列(deque)
一个线程安全的双向队列
""" deque 使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。 deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈: """ from collections import deque q = deque(['a', 'b', 'c']) q.append('x') q.appendleft('y') q
9.可变类型和不可变类型
可变类型:列表、字典
不可变类型:数字、字符串、元组
这里的可变不可变,是指内存中的那块内容(value)是否可以被改变
不可变类型
# 数字
In [93]: id(a)
Out[93]: 1850764656
In [94]: a += 1
In [95]: id(a)
Out[95]: 1850764688
# 字符串
In [88]: a = '123'
In [89]: id(a)
Out[89]: 942746951216
In [90]: a += '456'
In [91]: id(a)
Out[91]: 942746981576
# 元组
In [79]: a = (1,2,3)
In [80]: b = (4,5,6)
In [81]: id(a)
Out[81]: 942746089296
In [82]: id(b)
Out[82]: 942746396784
In [83]: a[1]
Out[83]: 2
In [84]: a[1] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-84-23f2cf2bdf70> in <module>()
----> 1 a[1] = 3
TypeError: 'tuple' object does not support item assignment
可变类型
# 列表
In [29]: a = [1,2,3]
In [30]: id(a)
Out[30]: 942745728456
In [31]: a.append(4)
In [32]: id(a)
Out[32]: 942745728456
# 字典
In [33]: c = {'k1':'v1','k2':'v2'}
In [34]: id(c)
Out[34]: 942746626232
In [35]: c['k3'] = 'v3'
In [36]: c
Out[36]: {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
In [37]: id(c)
Out[37]: 942746626232
字典的key只能是不可变类型,可变类型不可哈希
In [96]: dic = {1:'v1',2:'v2'}
In [97]: dic = {'k1':'v1','k2':'v2'}
In [98]: dic = {(1,2):'v1',(2,3):'v2'}
In [99]: dic = {[1,2]:'v1',[2,3]:'v2'}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-99-4e27abb80f56> in <module>()
----> 1 dic = {[1,2]:'v1',[2,3]:'v2'}
TypeError: unhashable type: 'list'
In [100]: dic = {{'k':'v'}:'v1',{'k1':'v1'}:'v2'}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-100-25f010250cc4> in <module>()
----> 1 dic = {{'k':'v'}:'v1',{'k1':'v1'}:'v2'}
TypeError: unhashable type: 'dict'
10.迭代器、生成器、可迭代对象
关于此部分内容大家请看我这篇文章
11.深浅拷贝
何为深浅拷贝?
In [49]: a = [1,2,3] In [50]: b = a In [51]: a.append(4) In [52]: a Out[52]: [1, 2, 3, 4] In [53]: b Out[53]: [1, 2, 3, 4]
唉?我们把a赋值给了b,结果a添加了一个元素,b也跟着添加了。这是为什么,我复制了一份不就和原来的没关系了吗?
这其实就是深拷贝,b = a其实是把a指向的那个列表的内存的引用给了b,当a指向的那个内存发生改变时,b也会同时发生变化。这就是深拷贝。
那我们不想拷贝它的引用,我们只想拷贝值怎么办?a.copy()就搞定了
In [54]: a = [1,2,3] In [55]: b = a.copy() # 浅拷贝,只拷贝当前变量所在内存中存储的值,而不是引用 In [56]: b Out[56]: [1, 2, 3] In [57]: a.append(4) In [58]: a
Out[58]: [1, 2, 3, 4] In [59]: b Out[59]: [1, 2, 3]
案例:名片管理系统
#1. 打印功能提示 print("="*50) print(" 名片管理系统 v0.1") print(" 1.添加一个名片") print(" 2.删除一个名片") print(" 3.修改一个名片") print(" 4.查询一个名片") print(" 5.显示所有名片") print(" 6.退出系统") print("="*50) #用来存储名片(列表) card_infors = [] while True: #2.获取用户的输入 num = int(input("请输入操作序列:")) #3.根据用户的输入执行相应的功能 if num==1: new_name = input("请输入新的名字:") new_qq = input("请输入新的qq:") new_weixin = input("请输入新的微信:") new_addr = input("请输入新的住址:") #定义一个新的字典,用来存储一个新的名片 new_infor ={} new_infor['name'] = new_name new_infor['qq'] = new_qq new_infor['weixin'] = new_weixin new_infor['addr'] = new_addr #将一个字典添加到列表中 card_infors.append(new_infor) print(card_infors) elif num==2: find_flag=0 del_name = input("删除的姓名是:") for temp in card_infors: if del_name == temp['name']: card_infors.remove(temp) find_flag = 1 print(card_infors) break if find_flag==0: print("查无此人") elif num==3: find_flag=0 name = input("你要修改的名片的姓名是:") for temp in card_infors: if name==temp['name']: temp['name'] = input("姓名:") temp['qq'] = input("qq:") temp['weixin'] = input("微信:") temp['addr'] = input("地址:") print("姓名\tQQ\t微信\t住址") print("%s\t%s\t%s\t%s\t"%(temp['name'],temp['qq'],temp['weixin'],temp['addr'])) find_flag=1 break if find_flag==0: print("查无此人") elif num==4: find_name = input("请输入要查找的名字:") find_flag = 0 #默认表示没有找到 for temp in card_infors: if find_name == temp['name']: print("%s\t%s\t%s\t%s\t"%(temp['name'],temp['qq'],temp['weixin'],temp['addr'])) find_flag = 1 break #else: #print("查无此人") #p判断是否找到了 if find_flag==0: print("查无此人") elif num==5: for temp in card_infors: print("%s\t%s\t%s\t%s\t"%(temp['name'],temp['qq'],temp['weixin'],temp['addr'])) elif num==6: break else: print("你输入的信息有误,请重新输入!")