python0x452_Python基础之第二篇详解

一、作用域

对作用域来说,只要变量在内存里面存在就可以使用:

1 if 1==1:2 name = 'saneri'

3 print name

二、三元运算

result = 值1 if 条件 else 值2

如果条件为真:result = 值1

如果条件为假:result = 值2

三、进制

二进制,01

八进制,01234567

十进制,0123456789

十六进制,0123456789ABCDE

对于Python 一切事物都是对象,对象基于类创建.类里面保存了对象的方法和功能:

通过type可以查看对象的类型

dir(类型名)查看类中提供的所有功能

help(类型名) 查看类中所有详细的功能

help(类型名.功能名) 查看类中某功能的详细信息.

dir(list)

私有方法'__add__', '__class__', '__contains__'可能有多种执行方式

非内置方法:'append', 'count', 'extend', 'index', 'insert' 只有一种执行方式,通过对象.方法来调用.

一、整数

创建数字方法

i = 10

i = int(10)

i = int("10",base=2)

1 divmod(10,3) 求商和余数 ---》分页2 all() 接收一个序列,判断,所有值都是真,返回真,负责返回假.3 any() 只要有一个是真,就是真.

class int(object):""" int(x=0) -> int or long

int(x, base=10) -> int or longConvert a number orstring to an integer, or return 0 ifno arguments

are given. If xisfloating point, the conversion truncates towards zero.

If xis outside the integer range, the function returns a longinstead.

If xis not a number or if base is given, then x must be a stringor

Unicodeobject representing an integer literal in the given base. The

literal can be preceded by'+' or '-'and be surrounded by whitespace.

Thebase defaults to 10. Valid bases are 0 and 2-36. Base 0means to

interpret thebase from the string asan integer literal.>>> int('0b100', base=0)4

"""def bit_length(self):"""返回表示该数字的时占用的最少位数"""

""" int.bit_length() -> intNumber of bits necessary to represent selfinbinary.>>> bin(37)'0b100101'

>>> (37).bit_length()6

""" return 0def conjugate(self,*args, **kwargs): # real signature unknown"""返回该复数的共轭复数"""

"""Returns self, the complex conjugate of any int."""pass

def __abs__(self):"""返回绝对值"""

"""x.__abs__() <==> abs(x)"""pass

def __add__(self, y):"""x.__add__(y) <==> x+y"""pass

def __and__(self, y):"""x.__and__(y) <==> x&y"""pass

def __cmp__(self, y):"""比较两个数大小"""

"""x.__cmp__(y) <==> cmp(x,y)"""pass

def __coerce__(self, y):"""强制生成一个元组"""

"""x.__coerce__(y) <==> coerce(x, y)"""pass

def __divmod__(self, y):"""相除,得到商和余数组成的元组"""

"""x.__divmod__(y) <==> divmod(x, y)"""pass

def __div__(self, y):"""x.__div__(y) <==> x/y"""pass

def __float__(self):"""转换为浮点类型"""

"""x.__float__() <==> float(x)"""pass

def __floordiv__(self, y):"""x.__floordiv__(y) <==> x//y"""pass

def __format__(self,*args, **kwargs): # real signature unknown

pass

def __getattribute__(self, name):"""x.__getattribute__('name') <==> x.name"""pass

def __getnewargs__(self,*args, **kwargs): # real signature unknown"""内部调用 __new__方法或创建对象时传入参数使用"""pass

def __hash__(self):"""如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""

"""x.__hash__() <==> hash(x)"""pass

def __hex__(self):"""返回当前数的 十六进制 表示"""

"""x.__hex__() <==> hex(x)"""pass

def __index__(self):"""用于切片,数字无意义"""

"""x[y:z] <==> x[y.__index__():z.__index__()]"""pass

def __init__(self, x,base=10): # known special case of int.__init__"""构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略"""

""" int(x=0) -> int or long

int(x, base=10) -> int or longConvert a number orstring to an integer, or return 0 ifno arguments

are given. If xisfloating point, the conversion truncates towards zero.

If xis outside the integer range, the function returns a longinstead.

If xis not a number or if base is given, then x must be a stringor

Unicodeobject representing an integer literal in the given base. The

literal can be preceded by'+' or '-'and be surrounded by whitespace.

Thebase defaults to 10. Valid bases are 0 and 2-36. Base 0means to

interpret thebase from the string asan integer literal.>>> int('0b100', base=0)4# (copiedfrom classdoc)"""pass

def __int__(self):"""转换为整数"""

"""x.__int__() <==> int(x)"""pass

def __invert__(self):"""x.__invert__() <==> ~x"""pass

def __long__(self):"""转换为长整数"""

"""x.__long__() <==> long(x)"""pass

def __lshift__(self, y):"""x.__lshift__(y) <==> x<

def __mod__(self, y):"""x.__mod__(y) <==> x%y"""pass

def __mul__(self, y):"""x.__mul__(y) <==> x*y"""pass

def __neg__(self):"""x.__neg__() <==> -x"""pass

@staticmethod # knowncaseof __new__

def __new__(S,*more):"""T.__new__(S, ...) -> a new object with type S, a subtype of T"""pass

def __nonzero__(self):"""x.__nonzero__() <==> x != 0"""pass

def __oct__(self):"""返回改值的 八进制 表示"""

"""x.__oct__() <==> oct(x)"""pass

def __or__(self, y):"""x.__or__(y) <==> x|y"""pass

def __pos__(self):"""x.__pos__() <==> +x"""pass

def __pow__(self, y, z=None):"""幂,次方"""

"""x.__pow__(y[, z]) <==> pow(x, y[, z])"""pass

def __radd__(self, y):"""x.__radd__(y) <==> y+x"""pass

def __rand__(self, y):"""x.__rand__(y) <==> y&x"""pass

def __rdivmod__(self, y):"""x.__rdivmod__(y) <==> divmod(y, x)"""pass

def __rdiv__(self, y):"""x.__rdiv__(y) <==> y/x"""pass

def __repr__(self):"""转化为解释器可读取的形式"""

"""x.__repr__() <==> repr(x)"""pass

def __str__(self):"""转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""

"""x.__str__() <==> str(x)"""pass

def __rfloordiv__(self, y):"""x.__rfloordiv__(y) <==> y//x"""pass

def __rlshift__(self, y):"""x.__rlshift__(y) <==> y<

def __rmod__(self, y):"""x.__rmod__(y) <==> y%x"""pass

def __rmul__(self, y):"""x.__rmul__(y) <==> y*x"""pass

def __ror__(self, y):"""x.__ror__(y) <==> y|x"""pass

def __rpow__(self, x, z=None):"""y.__rpow__(x[, z]) <==> pow(x, y[, z])"""pass

def __rrshift__(self, y):"""x.__rrshift__(y) <==> y>>x"""pass

def __rshift__(self, y):"""x.__rshift__(y) <==> x>>y"""pass

def __rsub__(self, y):"""x.__rsub__(y) <==> y-x"""pass

def __rtruediv__(self, y):"""x.__rtruediv__(y) <==> y/x"""pass

def __rxor__(self, y):"""x.__rxor__(y) <==> y^x"""pass

def __sub__(self, y):"""x.__sub__(y) <==> x-y"""pass

def __truediv__(self, y):"""x.__truediv__(y) <==> x/y"""pass

def __trunc__(self,*args, **kwargs):"""返回数值被截取为整形的值,在整形中无意义"""pass

def __xor__(self, y):"""x.__xor__(y) <==> x^y"""pass

denominator= property(lambda self: object(), lambda self, v: None, lambda self: None) # default

"""分母 = 1"""

"""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"""

int

二、长整型

可能如:2147483649、9223372036854775807

每个长整型都具备如下功能:

class long(object):""" long(x=0) -> long

long(x, base=10) -> longConvert a number orstring to a long integer, or return 0L ifno arguments

are given. If xisfloating point, the conversion truncates towards zero.

If xis not a number or if base is given, then x must be a stringor

Unicodeobject representing an integer literal in the given base. The

literal can be preceded by'+' or '-'and be surrounded by whitespace.

Thebase defaults to 10. Valid bases are 0 and 2-36. Base 0means to

interpret thebase from the string asan integer literal.>>> int('0b100', base=0)4L

""" def bit_length(self): # real signature unknown; restored from__doc__""" long.bit_length() -> int or longNumber of bits necessary to represent selfinbinary.>>> bin(37L)'0b100101'

>>> (37L).bit_length()6

""" return 0def conjugate(self,*args, **kwargs): # real signature unknown"""Returns self, the complex conjugate of any long."""pass

def __abs__(self): # real signature unknown; restoredfrom__doc__"""x.__abs__() <==> abs(x)"""pass

def __add__(self, y): # real signature unknown; restoredfrom__doc__"""x.__add__(y) <==> x+y"""pass

def __and__(self, y): # real signature unknown; restoredfrom__doc__"""x.__and__(y) <==> x&y"""pass

def __cmp__(self, y): # real signature unknown; restoredfrom__doc__"""x.__cmp__(y) <==> cmp(x,y)"""pass

def __coerce__(self, y): # real signature unknown; restoredfrom__doc__"""x.__coerce__(y) <==> coerce(x, y)"""pass

def __divmod__(self, y): # real signature unknown; restoredfrom__doc__"""x.__divmod__(y) <==> divmod(x, y)"""pass

def __div__(self, y): # real signature unknown; restoredfrom__doc__"""x.__div__(y) <==> x/y"""pass

def __float__(self): # real signature unknown; restoredfrom__doc__"""x.__float__() <==> float(x)"""pass

def __floordiv__(self, y): # real signature unknown; restoredfrom__doc__"""x.__floordiv__(y) <==> x//y"""pass

def __format__(self,*args, **kwargs): # real signature unknown

pass

def __getattribute__(self, name): # real signature unknown; restoredfrom__doc__"""x.__getattribute__('name') <==> x.name"""pass

def __getnewargs__(self,*args, **kwargs): # real signature unknown

pass

def __hash__(self): # real signature unknown; restoredfrom__doc__"""x.__hash__() <==> hash(x)"""pass

def __hex__(self): # real signature unknown; restoredfrom__doc__"""x.__hex__() <==> hex(x)"""pass

def __index__(self): # real signature unknown; restoredfrom__doc__"""x[y:z] <==> x[y.__index__():z.__index__()]"""pass

def __init__(self, x=0): # real signature unknown; restored from__doc__

pass

def __int__(self): # real signature unknown; restoredfrom__doc__"""x.__int__() <==> int(x)"""pass

def __invert__(self): # real signature unknown; restoredfrom__doc__"""x.__invert__() <==> ~x"""pass

def __long__(self): # real signature unknown; restoredfrom__doc__"""x.__long__() <==> long(x)"""pass

def __lshift__(self, y): # real signature unknown; restoredfrom__doc__"""x.__lshift__(y) <==> x<

def __mod__(self, y): # real signature unknown; restoredfrom__doc__"""x.__mod__(y) <==> x%y"""pass

def __mul__(self, y): # real signature unknown; restoredfrom__doc__"""x.__mul__(y) <==> x*y"""pass

def __neg__(self): # real signature unknown; restoredfrom__doc__"""x.__neg__() <==> -x"""pass

@staticmethod # knowncaseof __new__

def __new__(S,*more): # real signature unknown; restored from__doc__"""T.__new__(S, ...) -> a new object with type S, a subtype of T"""pass

def __nonzero__(self): # real signature unknown; restoredfrom__doc__"""x.__nonzero__() <==> x != 0"""pass

def __oct__(self): # real signature unknown; restoredfrom__doc__"""x.__oct__() <==> oct(x)"""pass

def __or__(self, y): # real signature unknown; restoredfrom__doc__"""x.__or__(y) <==> x|y"""pass

def __pos__(self): # real signature unknown; restoredfrom__doc__"""x.__pos__() <==> +x"""pass

def __pow__(self, y, z=None): # real signature unknown; restored from__doc__"""x.__pow__(y[, z]) <==> pow(x, y[, z])"""pass

def __radd__(self, y): # real signature unknown; restoredfrom__doc__"""x.__radd__(y) <==> y+x"""pass

def __rand__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rand__(y) <==> y&x"""pass

def __rdivmod__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rdivmod__(y) <==> divmod(y, x)"""pass

def __rdiv__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rdiv__(y) <==> y/x"""pass

def __repr__(self): # real signature unknown; restoredfrom__doc__"""x.__repr__() <==> repr(x)"""pass

def __rfloordiv__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rfloordiv__(y) <==> y//x"""pass

def __rlshift__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rlshift__(y) <==> y<

def __rmod__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rmod__(y) <==> y%x"""pass

def __rmul__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rmul__(y) <==> y*x"""pass

def __ror__(self, y): # real signature unknown; restoredfrom__doc__"""x.__ror__(y) <==> y|x"""pass

def __rpow__(self, x, z=None): # real signature unknown; restored from__doc__"""y.__rpow__(x[, z]) <==> pow(x, y[, z])"""pass

def __rrshift__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rrshift__(y) <==> y>>x"""pass

def __rshift__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rshift__(y) <==> x>>y"""pass

def __rsub__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rsub__(y) <==> y-x"""pass

def __rtruediv__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rtruediv__(y) <==> y/x"""pass

def __rxor__(self, y): # real signature unknown; restoredfrom__doc__"""x.__rxor__(y) <==> y^x"""pass

def __sizeof__(self,*args, **kwargs): # real signature unknown"""Returns size in memory, in bytes"""pass

def __str__(self): # real signature unknown; restoredfrom__doc__"""x.__str__() <==> str(x)"""pass

def __sub__(self, y): # real signature unknown; restoredfrom__doc__"""x.__sub__(y) <==> x-y"""pass

def __truediv__(self, y): # real signature unknown; restoredfrom__doc__"""x.__truediv__(y) <==> x/y"""pass

def __trunc__(self,*args, **kwargs): # real signature unknown"""Truncating an Integral returns itself."""pass

def __xor__(self, y): # real signature unknown; restoredfrom__doc__"""x.__xor__(y) <==> x^y"""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"""

long

三、浮点型

如:3.14、2.88

每个浮点型都具备如下功能:

class float(object):""" float(x) ->floating point number

Convert astring or number to a floating point number, ifpossible."""def as_integer_ratio(self):"""获取改值的最简比"""

""" float.as_integer_ratio() -> (int, int)

Return a pair of integers, whose ratioisexactly equal to the originalfloatand 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

def fromhex(self,string):"""将十六进制字符串转换成浮点型"""

""" float.fromhex(string) -> floatCreate a floating-point number from a hexadecimal string.>>> float.fromhex('0x1.ffffp10')2047.984375

>>> float.fromhex('-0x1p-1074')-4.9406564584124654e-324

""" return 0.0def hex(self):"""返回当前值的 16 进制表示"""

""" float.hex() -> stringReturn 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):"""x.__abs__() <==> abs(x)"""pass

def __add__(self, y):"""x.__add__(y) <==> x+y"""pass

def __coerce__(self, y):"""x.__coerce__(y) <==> coerce(x, y)"""pass

def __divmod__(self, y):"""x.__divmod__(y) <==> divmod(x, y)"""pass

def __div__(self, y):"""x.__div__(y) <==> x/y"""pass

def __eq__(self, y):"""x.__eq__(y) <==> x==y"""pass

def __float__(self):"""x.__float__() <==> float(x)"""pass

def __floordiv__(self, y):"""x.__floordiv__(y) <==> x//y"""pass

def __format__(self, format_spec):""" float.__format__(format_spec) -> stringFormats thefloataccording to format_spec.""" return ""def __getattribute__(self, name):"""x.__getattribute__('name') <==> x.name"""pass

def __getformat__(self, typestr):""" float.__getformat__(typestr) -> stringYou 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, y):"""x.__ge__(y) <==> x>=y"""pass

def __gt__(self, y):"""x.__gt__(y) <==> x>y"""pass

def __hash__(self):"""x.__hash__() <==> hash(x)"""pass

def __init__(self, x):

pass

def __int__(self):"""x.__int__() <==> int(x)"""pass

def __le__(self, y):"""x.__le__(y) <==> x<=y"""pass

def __long__(self):"""x.__long__() <==> long(x)"""pass

def __lt__(self, y):"""x.__lt__(y) <==> x

def __mod__(self, y):"""x.__mod__(y) <==> x%y"""pass

def __mul__(self, y):"""x.__mul__(y) <==> x*y"""pass

def __neg__(self):"""x.__neg__() <==> -x"""pass

@staticmethod # knowncaseof __new__

def __new__(S,*more):"""T.__new__(S, ...) -> a new object with type S, a subtype of T"""pass

def __ne__(self, y):"""x.__ne__(y) <==> x!=y"""pass

def __nonzero__(self):"""x.__nonzero__() <==> x != 0"""pass

def __pos__(self):"""x.__pos__() <==> +x"""pass

def __pow__(self, y, z=None):"""x.__pow__(y[, z]) <==> pow(x, y[, z])"""pass

def __radd__(self, y):"""x.__radd__(y) <==> y+x"""pass

def __rdivmod__(self, y):"""x.__rdivmod__(y) <==> divmod(y, x)"""pass

def __rdiv__(self, y):"""x.__rdiv__(y) <==> y/x"""pass

def __repr__(self):"""x.__repr__() <==> repr(x)"""pass

def __rfloordiv__(self, y):"""x.__rfloordiv__(y) <==> y//x"""pass

def __rmod__(self, y):"""x.__rmod__(y) <==> y%x"""pass

def __rmul__(self, y):"""x.__rmul__(y) <==> y*x"""pass

def __rpow__(self, x, z=None):"""y.__rpow__(x[, z]) <==> pow(x, y[, z])"""pass

def __rsub__(self, y):"""x.__rsub__(y) <==> y-x"""pass

def __rtruediv__(self, y):"""x.__rtruediv__(y) <==> y/x"""pass

def __setformat__(self, typestr, fmt):""" 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 inaddition can only be

one of the latter twoifit appears to match the underlying C reality.

Override the automatic determination of C-level floating point type.

This affects how floats are converted to andfrombinary strings."""pass

def __str__(self):"""x.__str__() <==> str(x)"""pass

def __sub__(self, y):"""x.__sub__(y) <==> x-y"""pass

def __truediv__(self, y):"""x.__truediv__(y) <==> x/y"""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"""

float

_hash__ 在字典查找中,哈希值用于快速比较字典的键

__hex__"""返回当前数的 十六进制 表示"""__oct__ 返回改值的 八进制 表示"""

四、字符串

如:'saneri'、'abcd'

每个字符串都具备如下功能:

1 """

2 str(object='') -> string3

4 Return a nice string representation of the object.5 If the argument is a string, the return value is the same object.6 """

7 defcapitalize(self):8 """首字母变大写"""

9 """

10 S.capitalize() -> string11

12 Return a copy of the string S with only its first character13 capitalized.14 """

15 return ""

16

17 def center(self, width, fillchar=None):18 """内容居中,width:总长度;fillchar:空白处填充内容,默认无"""

19 """

20 S.center(width[, fillchar]) -> string21 >>> s = "alex"22 >>> s.center(30, "*")23 '*************alex*************'24 Return S centered in a string of length width. Padding is25 done using the specified fill character (default is a space)26 """

27 return ""

28

29 def count(self, sub, start=None, end=None):30 """子序列个数"""

31 """

32 S.count(sub[, start[, end]]) -> int33 s.count("a",0,5) start,end找,下标的位置34 Return the number of non-overlapping occurrences of substring sub in35 string S[start:end]. Optional arguments start and end are interpreted36 as in slice notation.37 """

38 return039

40 def decode(self, encoding=None, errors=None):41 """解码"""

42 """

43 S.decode([encoding[,errors]]) -> object44

45 Decodes S using the codec registered for encoding. encoding defaults46 to the default encoding. errors may be given to set a different error47 handling scheme. Default is 'strict' meaning that encoding errors raise48 a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'49 as well as any other name registered with codecs.register_error that is50 able to handle UnicodeDecodeErrors.51 """

52 returnobject()53

54 def encode(self, encoding=None, errors=None):55 """编码,针对unicode"""

56 """

57 S.encode([encoding[,errors]]) -> object58

59 Encodes S using the codec registered for encoding. encoding defaults60 to the default encoding. errors may be given to set a different error61 handling scheme. Default is 'strict' meaning that encoding errors raise62 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and63 'xmlcharrefreplace' as well as any other name registered with64 codecs.register_error that is able to handle UnicodeEncodeErrors.65 """

66 returnobject()67

68 def endswith(self, suffix, start=None, end=None):69 """是否以 xxx 结束"""

70 """

71 S.endswith(suffix[, start[, end]]) -> bool72

73 Return True if S ends with the specified suffix, False otherwise.74 With optional start, test S beginning at that position.75 With optional end, stop comparing S at that position.76 suffix can also be a tuple of strings to try.77 """

78 returnFalse79

80 def expandtabs(self, tabsize=None):81 """将tab转换成空格,默认一个tab转换成8个空格"""

82 """

83 S.expandtabs([tabsize]) -> string84

85 Return a copy of S where all tab characters are expanded using spaces.86 If tabsize is not given, a tab size of 8 characters is assumed.87 """

88 return ""

89

90 def find(self, sub, start=None, end=None):91 """寻找子序列位置,如果没找到,则异常"""

92 """

93 S.find(sub [,start [,end]]) -> int94

95 Return the lowest index in S where substring sub is found,96 such that sub is contained within S[start:end]. Optional97 arguments start and end are interpreted as in slice notation.98

99 Return -1 on failure.100 """

101 return0102

103 def format(*args, **kwargs): #known special case of str.format

104 """字符串格式化,动态参数,将函数式编程时细说"""

105 """

106 S.format(*args, **kwargs) -> string107

108 Return a formatted version of S, using substitutions from args and kwargs.109 The substitutions are identified by braces ('{' and '}').110 """

111 pass

112

113 def index(self, sub, start=None, end=None):114 """子序列位置,如果没找到,则返回-1"""

115 S.index(sub [,start [,end]]) ->int116

117 Like S.find() but raise ValueError when the substring is notfound.118 """

119 return 0120

121 def isalnum(self):122 """ 是否是字母和数字 """

123 """

124 S.isalnum() ->bool125

126 Return True if all characters inS are alphanumeric127 and there is at least one character inS, False otherwise.128 """

129 return False130

131 def isalpha(self):132 """ 是否是字母 """

133 """

134 S.isalpha() ->bool135

136 Return True if all characters inS are alphabetic137 and there is at least one character inS, False otherwise.138 """

139 return False140

141 def isdigit(self):142 """ 是否是数字 """

143 """

144 S.isdigit() ->bool145

146 Return True if all characters inS are digits147 and there is at least one character inS, False otherwise.148 """

149 return False150

151 def islower(self):152 """ 是否小写 """

153 """

154 S.islower() ->bool155

156 Return True if all cased characters in S are lowercase and there is

157 at least one cased character inS, False otherwise.158 """

159 return False160

161 def isspace(self):162 """

163 S.isspace() ->bool164

165 Return True if all characters inS are whitespace166 and there is at least one character inS, False otherwise.167 """

168 return False169

170 def istitle(self):171 """

172 S.istitle() ->bool173

174 Return True if S is a titlecased string and there isat least one175 character inS, i.e. uppercase characters may only follow uncased176 characters andlowercase characters only cased ones. Return False177 otherwise.178 """

179 return False180

181 def isupper(self):182 """

183 S.isupper() ->bool184

185 Return True if all cased characters in S are uppercase and there is

186 at least one cased character inS, False otherwise.187 """

188 return False189

190 def join(self, iterable):191 """ 连接 """

192 """

193 S.join(iterable) ->string194

195 Return a string which is the concatenation of the strings inthe196 iterable. The separator between elements isS.197 """

198 return ""199

200 def ljust(self, width, fillchar=None):201 """ 内容左对齐,右侧填充 """

202 """

203 S.ljust(width[, fillchar]) ->string204

205 Return S left-justified in a string of length width. Padding is

206 done using the specified fill character (default isa space).207 """

208 return ""209

210 def lower(self):211 """ 变小写 """

212 """

213 S.lower() ->string214

215 Return a copy of the string S converted to lowercase.216 """

217 return ""218

219 def lstrip(self, chars=None):220 """ 移除左侧空白 """

221 """

222 S.lstrip([chars]) -> string orunicode223

224 Return a copy of the string S with leading whitespace removed.225 If chars is given and not None, remove characters inchars instead.226 If chars isunicode, S will be converted to unicode before stripping227 """

228 return ""229

230 def partition(self, sep):231 """ 分割,前,中,后三部分 """

232 """

233 S.partition(sep) ->(head, sep, tail)234

235 Search for the separator sep in S, and returnthe part before it,236 the separator itself, and the part after it. If the separator is not

237 found, return S andtwo empty strings.238 """

239 pass240

241 def replace(self, old, new, count=None):242 """ 替换 """

243 """

244 S.replace(old, new[, count]) ->string245

246 Return a copy of string S with all occurrences of substring247 old replaced by new. If the optional argument count is

248 given, only the first count occurrences are replaced.249 """

250 return ""251

252 def rfind(self, sub, start=None, end=None):253 """

254 S.rfind(sub [,start [,end]]) ->int255

256 Return the highest index in S where substring sub isfound,257 such that sub iscontained within S[start:end]. Optional258 arguments start and end are interpreted as inslice notation.259

260 Return -1on failure.261 """

262 return 0263

264 def rindex(self, sub, start=None, end=None):265 """

266 S.rindex(sub [,start [,end]]) ->int267

268 Like S.rfind() but raise ValueError when the substring is notfound.269 """

270 return 0271

272 def rjust(self, width, fillchar=None):273 """

274 S.rjust(width[, fillchar]) ->string275

276 Return S right-justified in a string of length width. Padding is

277 done using the specified fill character (default isa space)278 """

279 return ""280

281 def rpartition(self, sep):282 """

283 S.rpartition(sep) ->(head, sep, tail)284

285 Search for the separator sep in S, starting at the end of S, and return

286 the part before it, the separator itself, andthe part after it. If the287 separator is not found, return two empty strings andS.288 """

289 pass290

291 def rsplit(self, sep=None, maxsplit=None):292 """

293 S.rsplit([sep [,maxsplit]]) ->list of strings294

295 Return a list of the words inthe string S, using sep as the296 delimiter string, starting at the end of the string andworking297 to the front. If maxsplit isgiven, at most maxsplit splits are298 done. If sep is not specified or isNone, any whitespace string299 isa separator.300 """

301 return []302

303 def rstrip(self, chars=None):304 """

305 S.rstrip([chars]) -> string orunicode306

307 Return a copy of the string S with trailing whitespace removed.308 If chars is given and not None, remove characters inchars instead.309 If chars isunicode, S will be converted to unicode before stripping310 """

311 return ""312

313 def split(self, sep=None, maxsplit=None):314 """ 分割, maxsplit最多分割几次 """

315 """

316 S.split([sep [,maxsplit]]) ->list of strings317

318 Return a list of the words inthe string S, using sep as the319 delimiter string. If maxsplit isgiven, at most maxsplit320 splits are done. If sep is not specified or isNone, any321 whitespace string is a separator andempty strings are removed322 fromthe result.323 """

324 return []325

326 def splitlines(self, keepends=False):327 """ 根据换行分割 """

328 """

329 S.splitlines(keepends=False) ->list of strings330

331 Return a list of the lines inS, breaking at line boundaries.332 Line breaks are not included inthe resulting list unless keepends333 is given andtrue.334 """

335 return []336

337 def startswith(self, prefix, start=None, end=None):338 """ 是否起始 """

339 """

340 S.startswith(prefix[, start[, end]]) ->bool341

342 Return True ifS starts with the specified prefix, False otherwise.343 With optional start, test S beginning at that position.344 With optional end, stop comparing S at that position.345 prefix can also be a tuple of strings to try.346 """

347 return False348

349 def strip(self, chars=None):350 """ 移除两端空白 """

351 """

352 S.strip([chars]) -> string orunicode353

354 Return a copy of the string S with leading andtrailing355 whitespace removed.356 If chars is given and not None, remove characters inchars instead.357 If chars isunicode, S will be converted to unicode before stripping358 """

359 return ""360

361 def swapcase(self):362 """ 大写变小写,小写变大写 """

363 """

364 S.swapcase() ->string365

366 Return a copy of the string S with uppercase characters367 converted to lowercase andvice versa.368 """

369 return ""370

371 def title(self):372 """

373 S.title() ->string374

375 Return a titlecased version of S, i.e. words start with uppercase376 characters, all remaining cased characters have lowercase.377 """

378 return ""379

380 def translate(self, table, deletechars=None):381 """

382 转换,需要先做一个对应表,最后一个表示删除字符集合383 intab = "aeiou"

384 outtab = "12345"

385 trantab =maketrans(intab, outtab)386 str = "this is string example....wow!!!"

387 print str.translate(trantab, 'xm')388 """

389

390 """

391 S.translate(table [,deletechars]) ->string392

393 Return a copy of the string S, where all characters occurring394 in the optional argument deletechars are removed, andthe395 remaining characters have been mapped through the given396 translation table, which must be a string of length 256 orNone.397 If the table argument is None, no translation is applied and

398 the operation simply removes the characters indeletechars.399 """

400 return ""401

402 def upper(self):403 """

404 S.upper() ->string405

406 Return a copy of the string S converted to uppercase.407 """

408 return ""409

410 def zfill(self, width):411 """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""

412 """

413 S.zfill(width) ->string414

415 Pad a numeric string S with zeros on the left, to fill a field416 of the specified width. The string S isnever truncated.417 """

418 return ""419

420 def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown421 pass422

423 def _formatter_parser(self, *args, **kwargs): # real signature unknown424 pass425

426 def __add__(self, y):427 """ x.__add__(y) <==> x+y """

428 pass429

430 def __contains__(self, y):431 """ x.__contains__(y) <==> y in x """

432 pass433

434 def __eq__(self, y):435 """ x.__eq__(y) <==> x==y """

436 pass437

438 def __format__(self, format_spec):439 """

440 S.__format__(format_spec) ->string441

442 Return a formatted version of S as described by format_spec.443 """

444 return ""445

446 def __getattribute__(self, name):447 """ x.__getattribute__('name') <==> x.name """

448 pass449

450 def __getitem__(self, y):451 """ x.__getitem__(y) <==> x[y] """

452 pass453

454 def __getnewargs__(self, *args, **kwargs): # real signature unknown455 pass456

457 def __getslice__(self, i, j):458 """

459 x.__getslice__(i, j) <==>x[i:j]460

461 Use of negative indices is notsupported.462 """

463 pass464

465 def __ge__(self, y):466 """ x.__ge__(y) <==> x>=y """

467 pass468

469 def __gt__(self, y):470 """ x.__gt__(y) <==> x>y """

471 pass472

473 def __hash__(self):474 """ x.__hash__() <==> hash(x) """

475 pass476

477 def __init__(self, string=''): # known special case of str.__init__478 """

479 str(object='') ->string480

481 Return a nice string representation of the object.482 If the argument is a string, the return value isthe same object.483 #(copied from class doc)

484 """

485 pass486

487 def __len__(self):488 """ x.__len__() <==> len(x) """

489 pass490

491 def __le__(self, y):492 """ x.__le__(y) <==> x<=y """

493 pass494

495 def __lt__(self, y):496 """ x.__lt__(y) <==> x

497 pass498

499 def __mod__(self, y):500 """ x.__mod__(y) <==> x%y """

501 pass502

503 def __mul__(self, n):504 """ x.__mul__(n) <==> x*n """

505 pass506

507 @staticmethod # known case of __new__508 def __new__(S, *more):509 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """

510 pass511

512 def __ne__(self, y):513 """ x.__ne__(y) <==> x!=y """

514 pass515

516 def __repr__(self):517 """ x.__repr__() <==> repr(x) """

518 pass519

520 def __rmod__(self, y):521 """ x.__rmod__(y) <==> y%x """

522 pass523

524 def __rmul__(self, n):525 """ x.__rmul__(n) <==> n*x """

526 pass527

528 def __sizeof__(self):529 """ S.__sizeof__() -> size of S in memory, in bytes """

530 pass531

532 def __str__(self):533 """ x.__str__() <==> str(x) """

534 pass535

536 str

str

五、列表

List是处理和存放一组数据的列表

如:[11,22,33]、['saneri', 'alex']

每个列表都具备如下功能:

List操作包含以下函数:

cmp(list1, list2):    比较两个列表的元素,两个元素相同返回0,前大后小返回1,前小后大返回-1

len(list):                列表元素个数

max(list):              返回列表元素最大值

min(list):               返回列表元素最小值

list('var'):               将元素转换为列表

del L[1]                   删除指定下标的元素

del L[1:3]                删除指定下标范围的元素

List操作包含以下方法:

L.append('var')        append方法用于在列表的尾部追加元素,参数'var'是插入元素的值

L.insert(index,'var')     用于将对象插入到列表中,俩个参数,第一个是索引位置,第二个插入的元素对象.

L.pop()            返回列表最后一个元素,并从List中删除.

Lpop(index)         返回列表索引的元素,并删除.

L.count(var)          该元素在列表中出现的个数

L.index('var')         取出元素的位置(下标),无则抛出异常.

L.remove('var')        remove方法用于从列表中移除第一次的值(值如果有重复则删除第一个)

L.sort()           排序

L.reverse()          倒序

L.extend(list1)        extend方法用于将两个列表合并,将list1列表的值添加到L列表的后面。

Python列表脚本操作符:

List 中 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

Python列表截取:

Python的列表截取与字符串操作类型,如下所示:

L = ['spam', 'Spam', 'SPAM!','xusandu']

实例:

1 >>> ShoppingList = ['car','clothers','iphone'] //定义列表

2 >>> ShoppingList.append('Alex')             //在列表中插入'Alex'字符

3 >>> ShoppingList                 //查看列表

4 ['car', 'clothers', 'iphone', 'Alex']5 >>> ShoppingList.insert(0,'top')          //在列表下标为零处(即列表第一个元素),插入‘top’元素

6 >>>ShoppingList7 ['top', 'car', 'clothers', 'iphone', 'Alex']8 >>>

9 >>> ShoppingList[0]     //查看下标为零的元素

10 'top'

11 >>> ShoppingList[2]     //查看下标为2的元素

12 'clothers'

13 >>> ShoppingList[0] = 'car'   //将下标为0的元素(即‘top’字符)替换为‘car’

14 >>>ShoppingList15 ['car', 'car', 'clothers', 'iphone', 'Alex']16 >>> ShoppingList.pop()     //列表最后一个元素(Alex),并从List中删除掉

17 'Alex'

18 >>>ShoppingList19 ['car', 'car', 'clothers', 'iphone']20 >>>

21 >>> ShoppingList.remove('iphone') //从列表中移除'iphone'元素

22 >>>ShoppingList23 ['car', 'car', 'clothers']24 >>>

25 >>> ShoppingList.append('rain')26 >>> ShoppingList.count('car') //统计列表中元素'car'的个数

27 2

28 >>> 'car' in ShoppingList   //List列表中查找'car'元素,如果存在则返回Ture

29 True30 >>>

31 >>>ShoppingList32 ['car', 'car', 'clothers', 'rain']33 >>> ShoppingList.index('rain')34 3

35 >>>ShoppingList36 ['car', 'car', 'clothers', 'rain']37 >>> del ShoppingList[0] //使用del 函数删除List中下标为0的元素.

38 >>>ShoppingList39 ['car', 'clothers', 'rain']40 >>>

六、元组(tuple)

不可变序列-----元组 tuple

元组通过圆括号中用逗号分隔的项目定义,不可以添加和删除元组.

如:(11,22,33)、('saneri', 'alex')

每个元组都具备如下功能:connt,index

1 >>> name_tuple = ('a','b','c','a','b')2 >>>type(name_tuple)3

4 >>> name_tuple.count('a')5 2

6 >>> name_tuple.index('b') //获取b元素下标位置.

7 1

七、字典

字典是Python语言中唯一的映射类型。

映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希表。

字典对象是可变的,它是一个容器类型,能存储任意个数的Python对象,其中也可包括其他容器类型。

技巧:

字典中包含列表:dict = {"ZhangSan" : ['23','IT'],"Lisi" : ['22','dota']}

字典中包含字典:dict = {"Wangwu" : {"age" : 23,"job":"IT"},"Song" : {"age":22,"job":"dota"}}

Dict 操作包含以下方法:

D = {"ZhangSan" : ['23','IT'],"Lisi" : ['22','dota']}

D.clear()          清空字典D中的内容

D.keys()           查看字典所有主键

D.values()         查看字典所有value内容

D.popitem()        默认删除第一个键值

D.has_key('rain')     查询字典中是否有某个键

D['James'] = '23'     添加新item到字典

str(D)          输出字典可打印的字符串表示

del D['rain']      删除item

cmp(a,b)        首先比较主键长度,然后比较键大小,然后比较键值大小,(第一个大返回1,小返回-1,一样返回0)

D.fromkeys(seq[, value]))    fromkeys()方法从序列键和值设置为value来创建一个新的字典。实例如下:

1 seq = ('name', 'age', 'sex')2 dict =dict.fromkeys(seq)3 print "New Dictionary : %s" %str(dict)4

5 dict = dict.fromkeys(seq, 10)6 print "New Dictionary : %s" %str(dict)7

8 当我们运行上面的程序,它会产生以下结果:9 New Dictionary : {'age': None, 'name': None, 'sex': None}10 New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

fromkeys方法

setdefault()          setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

1 dict.setdefault(key, default=None)2 key --查找的键值.3

4 default --键不存在时,设置的默认键值。5 dict = {'Name': 'Zara', 'Age': 7}6

7 print "Value : %s" % dict.setdefault('Age', None)8 print "Value : %s" % dict.setdefault('Sex', None)9 以上实例输出结果为:10 Value : 7

11 Value : None

setdefault

每个字典具备如下功能:

1 classdict(object):2 """

3 dict() -> new empty dictionary4 dict(mapping) -> new dictionary initialized from a mapping object's5 (key, value) pairs6 dict(iterable) -> new dictionary initialized as if via:7 d = {}8 for k, v in iterable:9 d[k] = v10 dict(**kwargs) -> new dictionary initialized with the name=value pairs11 in the keyword argument list. For example: dict(one=1, two=2)12 """

13

14 def clear(self): #real signature unknown; restored from __doc__

15 """清除内容"""

16 """D.clear() -> None. Remove all items from D."""

17 pass

18

19 def copy(self): #real signature unknown; restored from __doc__

20 """浅拷贝"""

21 """D.copy() -> a shallow copy of D"""

22 pass

23

24 @staticmethod #known case

25 def fromkeys(S, v=None): #real signature unknown; restored from __doc__

26 """

27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.28 v defaults to None.29 """

30 pass

31

32 def get(self, k, d=None): #real signature unknown; restored from __doc__

33 """根据key获取值,d是默认值"""

34 """D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."""

35 pass

36

37 def has_key(self, k): #real signature unknown; restored from __doc__

38 """是否有key"""

39 """D.has_key(k) -> True if D has a key k, else False"""

40 returnFalse41

42 def items(self): #real signature unknown; restored from __doc__

43 """所有项的列表形式"""

44 """D.items() -> list of D's (key, value) pairs, as 2-tuples"""

45 return[]46

47 def iteritems(self): #real signature unknown; restored from __doc__

48 """项可迭代"""

49 """D.iteritems() -> an iterator over the (key, value) items of D"""

50 pass

51

52 def iterkeys(self): #real signature unknown; restored from __doc__

53 """key可迭代"""

54 """D.iterkeys() -> an iterator over the keys of D"""

55 pass

56

57 def itervalues(self): #real signature unknown; restored from __doc__

58 """value可迭代"""

59 """D.itervalues() -> an iterator over the values of D"""

60 pass

61

62 def keys(self): #real signature unknown; restored from __doc__

63 """所有的key列表"""

64 """D.keys() -> list of D's keys"""

65 return[]66

67 def pop(self, k, d=None): #real signature unknown; restored from __doc__

68 """获取并在字典中移除"""

69 """

70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value.71 If key is not found, d is returned if given, otherwise KeyError is raised72 """

73 pass

74

75 def popitem(self): #real signature unknown; restored from __doc__

76 """获取并在字典中移除"""

77 """

78 D.popitem() -> (k, v), remove and return some (key, value) pair as a79 2-tuple; but raise KeyError if D is empty.80 """

81 pass

82

83 def setdefault(self, k, d=None): #real signature unknown; restored from __doc__

84 """如果key不存在,则创建,如果存在,则返回已存在的值且不修改"""

85 """D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D"""

86 pass

87

88 def update(self, E=None, **F): #known special case of dict.update

89 """更新90 {'name':'alex', 'age': 18000}91 [('name','sbsbsb'),]92 """

93 """

94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F.95 If E present and has a .keys() method, does: for k in E: D[k] = E[k]96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v97 In either case, this is followed by: for k in F: D[k] = F[k]98 """

99 pass

100

101 def values(self): #real signature unknown; restored from __doc__

102 """所有的值"""

103 """D.values() -> list of D's values"""

104 return[]105

106 def viewitems(self): #real signature unknown; restored from __doc__

107 """所有项,只是将内容保存至view对象中"""

108 """D.viewitems() -> a set-like object providing a view on D's items"""

109 pass

110

111 def viewkeys(self): #real signature unknown; restored from __doc__

112 """D.viewkeys() -> a set-like object providing a view on D's keys"""

113 pass

114

115 def viewvalues(self): #real signature unknown; restored from __doc__

116 """D.viewvalues() -> an object providing a view on D's values"""

117 pass

118

119 def __cmp__(self, y): #real signature unknown; restored from __doc__

120 """x.__cmp__(y) <==> cmp(x,y)"""

121 pass

122

123 def __contains__(self, k): #real signature unknown; restored from __doc__

124 """D.__contains__(k) -> True if D has a key k, else False"""

125 returnFalse126

127 def __delitem__(self, y): #real signature unknown; restored from __doc__

128 """x.__delitem__(y) <==> del x[y]"""

129 pass

130

131 def __eq__(self, y): #real signature unknown; restored from __doc__

132 """x.__eq__(y) <==> x==y"""

133 pass

134

135 def __getattribute__(self, name): #real signature unknown; restored from __doc__

136 """x.__getattribute__('name') <==> x.name"""

137 pass

138

139 def __getitem__(self, y): #real signature unknown; restored from __doc__

140 """x.__getitem__(y) <==> x[y]"""

141 pass

142

143 def __ge__(self, y): #real signature unknown; restored from __doc__

144 """x.__ge__(y) <==> x>=y"""

145 pass

146

147 def __gt__(self, y): #real signature unknown; restored from __doc__

148 """x.__gt__(y) <==> x>y"""

149 pass

150

151 def __init__(self, seq=None, **kwargs): #known special case of dict.__init__

152 """

153 dict() -> new empty dictionary154 dict(mapping) -> new dictionary initialized from a mapping object's155 (key, value) pairs156 dict(iterable) -> new dictionary initialized as if via:157 d = {}158 for k, v in iterable:159 d[k] = v160 dict(**kwargs) -> new dictionary initialized with the name=value pairs161 in the keyword argument list. For example: dict(one=1, two=2)162 # (copied from class doc)163 """

164 pass

165

166 def __iter__(self): #real signature unknown; restored from __doc__

167 """x.__iter__() <==> iter(x)"""

168 pass

169

170 def __len__(self): #real signature unknown; restored from __doc__

171 """x.__len__() <==> len(x)"""

172 pass

173

174 def __le__(self, y): #real signature unknown; restored from __doc__

175 """x.__le__(y) <==> x<=y"""

176 pass

177

178 def __lt__(self, y): #real signature unknown; restored from __doc__

179 """x.__lt__(y) <==> x

180 pass

181

182 @staticmethod #known case of __new__

183 def __new__(S, *more): #real signature unknown; restored from __doc__

184 """T.__new__(S, ...) -> a new object with type S, a subtype of T"""

185 pass

186

187 def __ne__(self, y): #real signature unknown; restored from __doc__

188 """x.__ne__(y) <==> x!=y"""

189 pass

190

191 def __repr__(self): #real signature unknown; restored from __doc__

192 """x.__repr__() <==> repr(x)"""

193 pass

194

195 def __setitem__(self, i, y): #real signature unknown; restored from __doc__

196 """x.__setitem__(i, y) <==> x[i]=y"""

197 pass

198

199 def __sizeof__(self): #real signature unknown; restored from __doc__

200 """D.__sizeof__() -> size of D in memory, in bytes"""

201 pass

202

203 __hash__ =None204

205 dict

dict

八、set集合

set是一个无序且不重复的元素集合

a &b 交集

a | b 并集

a ^ b 取出非交集的数

a -b a里面有b里面没有

1 class set(object):2 """3 set() -> new empty set object

4 set(iterable) -> new set object

5

6 Build an unordered collection of unique elements.7 """8 def add(self, *args, **kwargs): # real signature unknown9 """添加"""

10 """11 Add an element to a set.12

13 This has no effect if the element isalready present.14 """15 pass16

17 def clear(self, *args, **kwargs): # real signature unknown18 """Remove all elements from this set."""

19 pass20

21 def copy(self, *args, **kwargs): # real signature unknown22 """Return a shallow copy of a set."""

23 pass24

25 def difference(self, *args, **kwargs): # real signature unknown26 """27 Return the difference of two or more sets as a new set.28

29 (i.e. all elements that are in this setbut not the others.)30 """31 pass32

33 def difference_update(self, *args, **kwargs): # real signature unknown34 """删除当前set中的所有包含在 new set 里的元素"""

35 """Remove all elements of another set from this set."""

36 pass37

38 def discard(self, *args, **kwargs): # real signature unknown39 """移除元素"""

40 """41 Remove an element from a set if it isa member.42

43 If the element is not a member, donothing.44 """45 pass46

47 def intersection(self, *args, **kwargs): # real signature unknown48 """取交集,新创建一个set"""

49 """50 Return the intersection of two or more sets as a new set.51

52 (i.e. elements that are common to all of the sets.)53 """54 pass55

56 def intersection_update(self, *args, **kwargs): # real signature unknown57 """取交集,修改原来set"""

58 """Update a set with the intersection of itself and another."""

59 pass60

61 def isdisjoint(self, *args, **kwargs): # real signature unknown62 """如果没有交集,返回true"""

63 """Return True if two sets have a null intersection."""

64 pass65

66 def issubset(self, *args, **kwargs): # real signature unknown67 """是否是子集"""

68 """Report whether another set contains this set."""

69 pass70

71 def issuperset(self, *args, **kwargs): # real signature unknown72 """是否是父集"""

73 """Report whether this set contains another set."""

74 pass75

76 def pop(self, *args, **kwargs): # real signature unknown77 """移除"""

78 """79 Remove and return an arbitrary setelement.80 Raises KeyError if the set isempty.81 """82 pass83

84 def remove(self, *args, **kwargs): # real signature unknown85 """移除"""

86 """87 Remove an element from a set; it must be a member.88

89 If the element isnot a member, raise a KeyError.90 """91 pass92

93 def symmetric_difference(self, *args, **kwargs): # real signature unknown94 """差集,创建新对象"""

95 """96 Return the symmetric difference of two sets as a new set.97

98 (i.e. all elements that are inexactly one of the sets.)99 """100 pass101

102 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown103 """差集,改变原来"""

104 """Update a set with the symmetric difference of itself and another."""

105 pass106

107 def union(self, *args, **kwargs): # real signature unknown108 """并集"""

109 """110 Return the union of sets as a new set.111

112 (i.e. all elements that are in either set.)113 """114 pass115

116 def update(self, *args, **kwargs): # real signature unknown117 """更新"""

118 """Update a set with the union of itself and others."""

119 pass120

121 def __and__(self, y): # real signature unknown; restored from__doc__122 """x.__and__(y) <==> x&y"""

123 pass124

125 def __cmp__(self, y): # real signature unknown; restored from__doc__126 """x.__cmp__(y) <==> cmp(x,y)"""

127 pass128

129 def __contains__(self, y): # real signature unknown; restored from__doc__130 """x.__contains__(y) <==> y in x."""

131 pass132

133 def __eq__(self, y): # real signature unknown; restored from__doc__134 """x.__eq__(y) <==> x==y"""

135 pass136

137 def __getattribute__(self, name): # real signature unknown; restored from__doc__138 """x.__getattribute__('name') <==> x.name"""

139 pass140

141 def __ge__(self, y): # real signature unknown; restored from__doc__142 """x.__ge__(y) <==> x>=y"""

143 pass144

145 def __gt__(self, y): # real signature unknown; restored from__doc__146 """x.__gt__(y) <==> x>y"""

147 pass148

149 def __iand__(self, y): # real signature unknown; restored from__doc__150 """x.__iand__(y) <==> x&=y"""

151 pass152

153 def __init__(self, seq=()): # known special case of set.__init__154 """155 set() -> new empty set object

156 set(iterable) -> new set object

157

158 Build an unordered collection of unique elements.159 # (copied from classdoc)160 """161 pass162

163 def __ior__(self, y): # real signature unknown; restored from__doc__164 """x.__ior__(y) <==> x|=y"""

165 pass166

167 def __isub__(self, y): # real signature unknown; restored from__doc__168 """x.__isub__(y) <==> x-=y"""

169 pass170

171 def __iter__(self): # real signature unknown; restored from__doc__172 """x.__iter__() <==> iter(x)"""

173 pass174

175 def __ixor__(self, y): # real signature unknown; restored from__doc__176 """x.__ixor__(y) <==> x^=y"""

177 pass178

179 def __len__(self): # real signature unknown; restored from__doc__180 """x.__len__() <==> len(x)"""

181 pass182

183 def __le__(self, y): # real signature unknown; restored from__doc__184 """x.__le__(y) <==> x<=y"""

185 pass186

187 def __lt__(self, y): # real signature unknown; restored from__doc__188 """x.__lt__(y) <==> x

189 pass190

191 @staticmethod # known caseof __new__192 def __new__(S, *more): # real signature unknown; restored from__doc__193 """T.__new__(S, ...) -> a new object with type S, a subtype of T"""

194 pass195

196 def __ne__(self, y): # real signature unknown; restored from__doc__197 """x.__ne__(y) <==> x!=y"""

198 pass199

200 def __or__(self, y): # real signature unknown; restored from__doc__201 """x.__or__(y) <==> x|y"""

202 pass203

204 def __rand__(self, y): # real signature unknown; restored from__doc__205 """x.__rand__(y) <==> y&x"""

206 pass207

208 def __reduce__(self, *args, **kwargs): # real signature unknown209 """Return state information for pickling."""

210 pass211

212 def __repr__(self): # real signature unknown; restored from__doc__213 """x.__repr__() <==> repr(x)"""

214 pass215

216 def __ror__(self, y): # real signature unknown; restored from__doc__217 """x.__ror__(y) <==> y|x"""

218 pass219

220 def __rsub__(self, y): # real signature unknown; restored from__doc__221 """x.__rsub__(y) <==> y-x"""

222 pass223

224 def __rxor__(self, y): # real signature unknown; restored from__doc__225 """x.__rxor__(y) <==> y^x"""

226 pass227

228 def __sizeof__(self): # real signature unknown; restored from__doc__229 """S.__sizeof__() -> size of S in memory, in bytes"""

230 pass231

232 def __sub__(self, y): # real signature unknown; restored from__doc__233 """x.__sub__(y) <==> x-y"""

234 pass235

236 def __xor__(self, y): # real signature unknown; restored from__doc__237 """x.__xor__(y) <==> x^y"""

238 pass239

240 __hash__ =None241 复制代码

set

1 L.set()2 >>> txt1 = [1,2,3,4,5]3 >>> txt2 = [2,4,6,7]4 >>> txt3 = list(set(txt1 +txt2))5 >>>

6 >>>print txt37 [1, 2, 3, 4, 5, 6, 7]8 >>>

九、collection系列:

1、计数器(counter)

Counter是对字典类型的补充,用于追踪值的出现次数。

具备字典的所有功能 + 自己的功能:

1 c = Counter('abcdeabcdabcaba')2 print c3 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

2、有序字典(orderedDict )

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

3、默认字典(defaultdict) defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。

需求:

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。

即: {'k1': 大于66 , 'k2': 小于66}defaultdict字典解决方法

1 values = [11, 22, 33,44,55,66,77,88,99,90]2

3 my_dict ={}4

5 for value invalues:6 if value>66:7 if my_dict.has_key('k1'):8 my_dict['k1'].append(value)9 else:10 my_dict['k1'] =[value]11 else:12 if my_dict.has_key('k2'):13 my_dict['k2'].append(value)14 else:15 my_dict['k2'] = [value]

原生字典解决方法

1 from collections importdefaultdict2

3 values = [11, 22, 33,44,55,66,77,88,99,90]4

5 my_dict =defaultdict(list)6

7 for value invalues:8 if value>66:9 my_dict['k1'].append(value)10 else:11 my_dict['k2'].append(value)

defaultdict字典解决方法

4、可命名元组(namedtuple)

根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型.

1 import collections2 Mytuple = collections.namedtuple('Mytuple',['x','y','z'])3 new = Mytuple(1,2,3)4 print new

5 Mytuple(x=1, y=2, z=3)

5、双向队列(deque)

两边都可以存取,线程安全的)   在collection模块中

单向队列:先进先出(FIFO)

栈:弹夹(后进的先出) 再Queue模块中

1 >>>import Queue2 >>> Q = Queue.Queue(10) 最多插入10个数3 >>> Q.put(1) 向队列中添加值4 >>> Q.put(2)5 >>> Q.put(3)6 >>> Q.put(4)7 Q.get()

一、迭代器

对于Python 列表的 for 循环,他的内部原理:查看下一个元素是否存在,如果存在,则取出,如果不存在,则报异常 StopIteration。(python内部对异常已处理)

listiterator

二、生成器

range不是生成器 而 xrange 是生成器

readlines不是生成器 而 xreadlines 是生成器

1 >>> print range(10)2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]3 >>> print xrange(10)4 xrange(10)

生成器内部基于yield创建,即:对于生成器只有使用时才创建,从而不避免内存浪费

练习:有如下列表:

[13, 22, 6, 99, 11]

请按照一下规则计算:13 和 22 比较,将大的值放在右侧,即:[13, 22, 6, 99, 11]22 和 6 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11]22 和 99 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11]99 和 42 比较,将大的值放在右侧,即:[13, 6, 22, 11, 99,]13 和 6 比较,将大的值放在右侧,即:[6, 13, 22, 11, 99,]

...

解析:

li = [13, 22, 6, 99, 11]

for m in range(len(li)-1):

for n in range(m+1, len(li)):

if li[m]> li[n]:

temp = li[n]

li[n] = li[m]

li[m] = temp

print li

让a和b的值互换位置:

1 >>> a = 123

2 >>> b = 321

3 >>>a,b4 (123, 321)5 >>> temp =a6 >>>temp7 123

8 >>> a =b9 >>>a10 321

11 >>> b =temp12 >>>a,b13 (321, 123)14 >>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值