Python入学第二天知识
第一个知识点:对于Python,一切事物都是对象,对象基于类创建
例如:"huyakun","你好",8,['北京','上海','深圳','广州']这些值都是对象,并且是不同类的生成的对象。
如何查看类的功能以及方法:
其他类的查看方式亦是如此。
一、整数型
如:8、88、99、100
每一个整数都具备如下功能:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object 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): """ 返回表示该数字的时占用的最少位数 """ """ 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 def __abs__(self): """ 返回绝对值 """ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(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 long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object 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): """ 转换为整数 """ """ 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<<y """ pass 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 # known case of __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<<x """ pass 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"""
随堂练习:
#bit_length() 表示该数字的时占用的最少位 >>> age = 30 >>> age.bit_length() 5 >>> #__abs__()取绝对值的两种方式 >>> age = -30 >>> age.__abs__() 30 >>> >>> abs(-30)#直接赋值去绝对值 30 >>> #__add__()加法不是内置的,有两种方法 >>> age.__add__(100) 70 >>> >>> 1+1 2 >>> # __divmod_ 页面分页时常用 all_item = 95 pager = 10 result = all_item.__divmod__(10) print (result) >>>(9,5)返回一个元组 #__eq__ 判断两个值是否相等 age = 26 result = age.__eq__(28) print(result) >>>False(返回一个布尔值) #_float_() 转换浮点型 age=26 print(type(age)) result = age.__float__() print(type(result)) >>><class 'int'> #第一打印查询类型是int >>><class 'float'>#第二次打印查询类型是float
二、字符串
type()查看类型 dir()查看类的成员
例如:name = "huyakun" >>> print (type(name)) >>>> <class 'str'>
>>>print(dir(name)) >>>>
name = str('huyakun') #str类的__init__
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class str(object): 2 """ 3 str(object='') -> str 4 str(bytes_or_buffer[, encoding[, errors]]) -> str 5 6 Create a new string object from the given object. If encoding or 7 errors is specified, then the object must expose a data buffer 8 that will be decoded using the given encoding and error handler. 9 Otherwise, returns the result of object.__str__() (if defined) 10 or repr(object). 11 encoding defaults to sys.getdefaultencoding(). 12 errors defaults to 'strict'. 13 """ 14 def capitalize(self): # real signature unknown; restored from __doc__ 15 """ 16 S.capitalize() -> str 17 18 Return a capitalized version of S, i.e. make the first character 19 have upper case and the rest lower case. 20 """ 21 return "" 22 23 def casefold(self): # real signature unknown; restored from __doc__ 24 """ 首字母变大写 """ 25 """ 26 S.casefold() -> str 27 28 Return a version of S suitable for caseless comparisons. 29 """ 30 return "" 31 32 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ 33 """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """ 34 """ 35 S.center(width[, fillchar]) -> str 36 37 Return S centered in a string of length width. Padding is 38 done using the specified fill character (default is a space) 39 """ 40 return "" 41 42 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 43 """ 子序列个数 """ 44 """ 45 S.count(sub[, start[, end]]) -> int 46 47 Return the number of non-overlapping occurrences of substring sub in 48 string S[start:end]. Optional arguments start and end are 49 interpreted as in slice notation. 50 """ 51 return 0 52 53 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ 54 """ 编码,针对unicode """ 55 """ 56 S.encode(encoding='utf-8', errors='strict') -> bytes 57 58 Encode S using the codec registered for encoding. Default encoding 59 is 'utf-8'. errors may be given to set a different error 60 handling scheme. Default is 'strict' meaning that encoding errors raise 61 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 62 'xmlcharrefreplace' as well as any other name registered with 63 codecs.register_error that can handle UnicodeEncodeErrors. 64 """ 65 return b"" 66 67 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ 68 """ 是否以 xxx 结束 """ 69 """ 70 S.endswith(suffix[, start[, end]]) -> bool 71 72 Return True if S ends with the specified suffix, False otherwise. 73 With optional start, test S beginning at that position. 74 With optional end, stop comparing S at that position. 75 suffix can also be a tuple of strings to try. 76 """ 77 return False 78 79 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ 80 """ 将tab转换成空格,默认一个tab转换成8个空格 """ 81 """ 82 S.expandtabs(tabsize=8) -> str 83 84 Return a copy of S where all tab characters are expanded using spaces. 85 If tabsize is not given, a tab size of 8 characters is assumed. 86 """ 87 return "" 88 89 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 90 """ 寻找子序列位置,如果没找到,返回 -1 """ 91 """ 92 S.find(sub[, start[, end]]) -> int 93 94 Return the lowest index in S where substring sub is found, 95 such that sub is contained within S[start:end]. Optional 96 arguments start and end are interpreted as in slice notation. 97 98 Return -1 on failure. 99 """ 100 return 0 101 102 def format(*args, **kwargs): # known special case of str.format 103 """ 字符串格式化,动态参数,将函数式编程时细说 """ 104 """ 105 S.format(*args, **kwargs) -> str 106 107 Return a formatted version of S, using substitutions from args and kwargs. 108 The substitutions are identified by braces ('{' and '}'). 109 """ 110 pass 111 112 def format_map(self, mapping): # real signature unknown; restored from __doc__ 113 """ 114 S.format_map(mapping) -> str 115 116 Return a formatted version of S, using substitutions from mapping. 117 The substitutions are identified by braces ('{' and '}'). 118 """ 119 return "" 120 121 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 122 """ 子序列位置,如果没找到,报错 """ 123 """ 124 S.index(sub[, start[, end]]) -> int 125 126 Like S.find() but raise ValueError when the substring is not found. 127 """ 128 return 0 129 130 def isalnum(self): # real signature unknown; restored from __doc__ 131 """ 是否是字母和数字 """ 132 """ 133 S.isalnum() -> bool 134 135 Return True if all characters in S are alphanumeric 136 and there is at least one character in S, False otherwise. 137 """ 138 return False 139 140 def isalpha(self): # real signature unknown; restored from __doc__ 141 """ 是否是字母 """ 142 """ 143 S.isalpha() -> bool 144 145 Return True if all characters in S are alphabetic 146 and there is at least one character in S, False otherwise. 147 """ 148 return False 149 150 def isdecimal(self): # real signature unknown; restored from __doc__ 151 """ 152 S.isdecimal() -> bool 153 154 Return True if there are only decimal characters in S, 155 False otherwise. 156 """ 157 return False 158 159 def isdigit(self): # real signature unknown; restored from __doc__ 160 """ 是否是数字 """ 161 """ 162 S.isdigit() -> bool 163 164 Return True if all characters in S are digits 165 and there is at least one character in S, False otherwise. 166 """ 167 return False 168 169 def isidentifier(self): # real signature unknown; restored from __doc__ 170 """ 171 S.isidentifier() -> bool 172 173 Return True if S is a valid identifier according 174 to the language definition. 175 176 Use keyword.iskeyword() to test for reserved identifiers 177 such as "def" and "class". 178 """ 179 return False 180 181 def islower(self): # real signature unknown; restored from __doc__ 182 """ 是否小写 """ 183 """ 184 S.islower() -> bool 185 186 Return True if all cased characters in S are lowercase and there is 187 at least one cased character in S, False otherwise. 188 """ 189 return False 190 191 def isnumeric(self): # real signature unknown; restored from __doc__ 192 """ 193 S.isnumeric() -> bool 194 195 Return True if there are only numeric characters in S, 196 False otherwise. 197 """ 198 return False 199 200 def isprintable(self): # real signature unknown; restored from __doc__ 201 """ 202 S.isprintable() -> bool 203 204 Return True if all characters in S are considered 205 printable in repr() or S is empty, False otherwise. 206 """ 207 return False 208 209 def isspace(self): # real signature unknown; restored from __doc__ 210 """ 211 S.isspace() -> bool 212 213 Return True if all characters in S are whitespace 214 and there is at least one character in S, False otherwise. 215 """ 216 return False 217 218 def istitle(self): # real signature unknown; restored from __doc__ 219 """ 220 S.istitle() -> bool 221 222 Return True if S is a titlecased string and there is at least one 223 character in S, i.e. upper- and titlecase characters may only 224 follow uncased characters and lowercase characters only cased ones. 225 Return False otherwise. 226 """ 227 return False 228 229 def isupper(self): # real signature unknown; restored from __doc__ 230 """ 231 S.isupper() -> bool 232 233 Return True if all cased characters in S are uppercase and there is 234 at least one cased character in S, False otherwise. 235 """ 236 return False 237 238 def join(self, iterable): # real signature unknown; restored from __doc__ 239 """ 连接 """ 240 """ 241 S.join(iterable) -> str 242 243 Return a string which is the concatenation of the strings in the 244 iterable. The separator between elements is S. 245 """ 246 return "" 247 248 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 249 """ 内容左对齐,右侧填充 """ 250 """ 251 S.ljust(width[, fillchar]) -> str 252 253 Return S left-justified in a Unicode string of length width. Padding is 254 done using the specified fill character (default is a space). 255 """ 256 return "" 257 258 def lower(self): # real signature unknown; restored from __doc__ 259 """ 变小写 """ 260 """ 261 S.lower() -> str 262 263 Return a copy of the string S converted to lowercase. 264 """ 265 return "" 266 267 def lstrip(self, chars=None): # real signature unknown; restored from __doc__ 268 """ 移除左侧空白 """ 269 """ 270 S.lstrip([chars]) -> str 271 272 Return a copy of the string S with leading whitespace removed. 273 If chars is given and not None, remove characters in chars instead. 274 """ 275 return "" 276 277 def maketrans(self, *args, **kwargs): # real signature unknown 278 """ 279 Return a translation table usable for str.translate(). 280 281 If there is only one argument, it must be a dictionary mapping Unicode 282 ordinals (integers) or characters to Unicode ordinals, strings or None. 283 Character keys will be then converted to ordinals. 284 If there are two arguments, they must be strings of equal length, and 285 in the resulting dictionary, each character in x will be mapped to the 286 character at the same position in y. If there is a third argument, it 287 must be a string, whose characters will be mapped to None in the result. 288 """ 289 pass 290 291 def partition(self, sep): # real signature unknown; restored from __doc__ 292 """ 分割,前,中,后三部分 """ 293 """ 294 S.partition(sep) -> (head, sep, tail) 295 296 Search for the separator sep in S, and return the part before it, 297 the separator itself, and the part after it. If the separator is not 298 found, return S and two empty strings. 299 """ 300 pass 301 302 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ 303 """ 替换 """ 304 """ 305 S.replace(old, new[, count]) -> str 306 307 Return a copy of S with all occurrences of substring 308 old replaced by new. If the optional argument count is 309 given, only the first count occurrences are replaced. 310 """ 311 return "" 312 313 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 314 """ 315 S.rfind(sub[, start[, end]]) -> int 316 317 Return the highest index in S where substring sub is found, 318 such that sub is contained within S[start:end]. Optional 319 arguments start and end are interpreted as in slice notation. 320 321 Return -1 on failure. 322 """ 323 return 0 324 325 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 326 """ 327 S.rindex(sub[, start[, end]]) -> int 328 329 Like S.rfind() but raise ValueError when the substring is not found. 330 """ 331 return 0 332 333 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 334 """ 335 S.rjust(width[, fillchar]) -> str 336 337 Return S right-justified in a string of length width. Padding is 338 done using the specified fill character (default is a space). 339 """ 340 return "" 341 342 def rpartition(self, sep): # real signature unknown; restored from __doc__ 343 """ 344 S.rpartition(sep) -> (head, sep, tail) 345 346 Search for the separator sep in S, starting at the end of S, and return 347 the part before it, the separator itself, and the part after it. If the 348 separator is not found, return two empty strings and S. 349 """ 350 pass 351 352 def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 353 """ 354 S.rsplit(sep=None, maxsplit=-1) -> list of strings 355 356 Return a list of the words in S, using sep as the 357 delimiter string, starting at the end of the string and 358 working to the front. If maxsplit is given, at most maxsplit 359 splits are done. If sep is not specified, any whitespace string 360 is a separator. 361 """ 362 return [] 363 364 def rstrip(self, chars=None): # real signature unknown; restored from __doc__ 365 """ 366 S.rstrip([chars]) -> str 367 368 Return a copy of the string S with trailing whitespace removed. 369 If chars is given and not None, remove characters in chars instead. 370 """ 371 return "" 372 373 def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 374 """ 375 S.split(sep=None, maxsplit=-1) -> list of strings 376 377 Return a list of the words in S, using sep as the 378 delimiter string. If maxsplit is given, at most maxsplit 379 splits are done. If sep is not specified or is None, any 380 whitespace string is a separator and empty strings are 381 removed from the result. 382 """ 383 return [] 384 385 def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ 386 """ 分割, maxsplit最多分割几次 """ 387 """ 388 S.splitlines([keepends]) -> list of strings 389 390 Return a list of the lines in S, breaking at line boundaries. 391 Line breaks are not included in the resulting list unless keepends 392 is given and true. 393 """ 394 return [] 395 396 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ 397 """ 是否起始 """ 398 """ 399 S.startswith(prefix[, start[, end]]) -> bool 400 401 Return True if S starts with the specified prefix, False otherwise. 402 With optional start, test S beginning at that position. 403 With optional end, stop comparing S at that position. 404 prefix can also be a tuple of strings to try. 405 """ 406 return False 407 408 def strip(self, chars=None): # real signature unknown; restored from __doc__ 409 """ 移除两段空白 """ 410 """ 411 S.strip([chars]) -> str 412 413 Return a copy of the string S with leading and trailing 414 whitespace removed. 415 If chars is given and not None, remove characters in chars instead. 416 """ 417 return "" 418 419 def swapcase(self): # real signature unknown; restored from __doc__ 420 """ 大写变小写,小写变大写 """ 421 """ 422 S.swapcase() -> str 423 424 Return a copy of S with uppercase characters converted to lowercase 425 and vice versa. 426 """ 427 return "" 428 429 def title(self): # real signature unknown; restored from __doc__ 430 """ 431 S.title() -> str 432 433 Return a titlecased version of S, i.e. words start with title case 434 characters, all remaining cased characters have lower case. 435 """ 436 return "" 437 438 def translate(self, table): # real signature unknown; restored from __doc__ 439 转换,需要先做一个对应表,最后一个表示删除字符集合 440 """ 441 S.translate(table) -> str 442 443 Return a copy of the string S in which each character has been mapped 444 through the given translation table. The table must implement 445 lookup/indexing via __getitem__, for instance a dictionary or list, 446 mapping Unicode ordinals to Unicode ordinals, strings, or None. If 447 this operation raises LookupError, the character is left untouched. 448 Characters mapped to None are deleted. 449 """ 450 return "" 451 452 def upper(self): # real signature unknown; restored from __doc__ 453 """ 454 S.upper() -> str 455 456 Return a copy of S converted to uppercase. 457 """ 458 return "" 459 460 def zfill(self, width): # real signature unknown; restored from __doc__ 461 """方法返回指定长度的字符串,原字符串右对齐,前面填充0。""" 462 """ 463 S.zfill(width) -> str 464 465 Pad a numeric string S with zeros on the left, to fill a field 466 of the specified width. The string S is never truncated. 467 """ 468 return "" 469 470 def __add__(self, *args, **kwargs): # real signature unknown 471 """ Return self+value. """ 472 pass 473 474 def __contains__(self, *args, **kwargs): # real signature unknown 475 """ Return key in self. """ 476 pass 477 478 def __eq__(self, *args, **kwargs): # real signature unknown 479 """ Return self==value. """ 480 pass 481 482 def __format__(self, format_spec): # real signature unknown; restored from __doc__ 483 """ 484 S.__format__(format_spec) -> str 485 486 Return a formatted version of S as described by format_spec. 487 """ 488 return "" 489 490 def __getattribute__(self, *args, **kwargs): # real signature unknown 491 """ Return getattr(self, name). """ 492 pass 493 494 def __getitem__(self, *args, **kwargs): # real signature unknown 495 """ Return self[key]. """ 496 pass 497 498 def __getnewargs__(self, *args, **kwargs): # real signature unknown 499 pass 500 501 def __ge__(self, *args, **kwargs): # real signature unknown 502 """ Return self>=value. """ 503 pass 504 505 def __gt__(self, *args, **kwargs): # real signature unknown 506 """ Return self>value. """ 507 pass 508 509 def __hash__(self, *args, **kwargs): # real signature unknown 510 """ Return hash(self). """ 511 pass 512 513 def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ 514 """ 515 str(object='') -> str 516 str(bytes_or_buffer[, encoding[, errors]]) -> str 517 518 Create a new string object from the given object. If encoding or 519 errors is specified, then the object must expose a data buffer 520 that will be decoded using the given encoding and error handler. 521 Otherwise, returns the result of object.__str__() (if defined) 522 or repr(object). 523 encoding defaults to sys.getdefaultencoding(). 524 errors defaults to 'strict'. 525 # (copied from class doc) 526 """ 527 pass 528 529 def __iter__(self, *args, **kwargs): # real signature unknown 530 """ Implement iter(self). """ 531 pass 532 533 def __len__(self, *args, **kwargs): # real signature unknown 534 """ Return len(self). """ 535 pass 536 537 def __le__(self, *args, **kwargs): # real signature unknown 538 """ Return self<=value. """ 539 pass 540 541 def __lt__(self, *args, **kwargs): # real signature unknown 542 """ Return self<value. """ 543 pass 544 545 def __mod__(self, *args, **kwargs): # real signature unknown 546 """ Return self%value. """ 547 pass 548 549 def __mul__(self, *args, **kwargs): # real signature unknown 550 """ Return self*value.n """ 551 pass 552 553 @staticmethod # known case of __new__ 554 def __new__(*args, **kwargs): # real signature unknown 555 """ Create and return a new object. See help(type) for accurate signature. """ 556 pass 557 558 def __ne__(self, *args, **kwargs): # real signature unknown 559 """ Return self!=value. """ 560 pass 561 562 def __repr__(self, *args, **kwargs): # real signature unknown 563 """ Return repr(self). """ 564 pass 565 566 def __rmod__(self, *args, **kwargs): # real signature unknown 567 """ Return value%self. """ 568 pass 569 570 def __rmul__(self, *args, **kwargs): # real signature unknown 571 """ Return self*value. """ 572 pass 573 574 def __sizeof__(self): # real signature unknown; restored from __doc__ 575 """ S.__sizeof__() -> size of S in memory, in bytes """ 576 pass 577 578 def __str__(self, *args, **kwargs): # real signature unknown 579 """ Return str(self). """ 580 pass 581 582 583 class super(object): 584 """ 585 super() -> same as super(__class__, <first argument>) 586 super(type) -> unbound super object 587 super(type, obj) -> bound super object; requires isinstance(obj, type) 588 super(type, type2) -> bound super object; requires issubclass(type2, type) 589 Typical use to call a cooperative superclass method: 590 class C(B): 591 def meth(self, arg): 592 super().meth(arg) 593 This works for class methods too: 594 class C(B): 595 @classmethod 596 def cmeth(cls, arg): 597 super().cmeth(arg) 598 """ 599 def __getattribute__(self, *args, **kwargs): # real signature unknown 600 """ Return getattr(self, name). """ 601 pass 602 603 def __get__(self, *args, **kwargs): # real signature unknown 604 """ Return an attribute of instance, which is of type owner. """ 605 pass 606 607 def __init__(self, type1=None, type2=None): # known special case of super.__init__ 608 """ 609 super() -> same as super(__class__, <first argument>) 610 super(type) -> unbound super object 611 super(type, obj) -> bound super object; requires isinstance(obj, type) 612 super(type, type2) -> bound super object; requires issubclass(type2, type) 613 Typical use to call a cooperative superclass method: 614 class C(B): 615 def meth(self, arg): 616 super().meth(arg) 617 This works for class methods too: 618 class C(B): 619 @classmethod 620 def cmeth(cls, arg): 621 super().cmeth(arg) 622 623 # (copied from class doc) 624 """ 625 pass 626 627 @staticmethod # known case of __new__ 628 def __new__(*args, **kwargs): # real signature unknown 629 """ Create and return a new object. See help(type) for accurate signature. """ 630 pass 631 632 def __repr__(self, *args, **kwargs): # real signature unknown 633 """ Return repr(self). """ 634 pass 635 636 __self_class__ = property(lambda self: type(object)) 637 """the type of the instance invoking super(); may be None 638 639 :type: type 640 """ 641 642 __self__ = property(lambda self: type(object)) 643 """the instance invoking super(); may be None 644 645 :type: type 646 """ 647 648 __thisclass__ = property(lambda self: type(object)) 649 """the class invoking super() 650 651 :type: type 652 """ 653 654 655 656 class SyntaxWarning(Warning): 657 """ Base class for warnings about dubious syntax. """ 658 def __init__(self, *args, **kwargs): # real signature unknown 659 pass 660 661 @staticmethod # known case of __new__ 662 def __new__(*args, **kwargs): # real signature unknown 663 """ Create and return a new object. See help(type) for accurate signature. """ 664 pass 665 666 667 class SystemError(Exception): 668 """ 669 Internal error in the Python interpreter. 670 671 Please report this to the Python maintainer, along with the traceback, 672 the Python version, and the hardware/OS platform and version. 673 """ 674 def __init__(self, *args, **kwargs): # real signature unknown 675 pass 676 677 @staticmethod # known case of __new__ 678 def __new__(*args, **kwargs): # real signature unknown 679 """ Create and return a new object. See help(type) for accurate signature. """ 680 pass 681 682 683 class SystemExit(BaseException): 684 """ Request to exit from the interpreter. """ 685 def __init__(self, *args, **kwargs): # real signature unknown 686 pass 687 688 code = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 689 """exception code""" 690 691 692 693 class TabError(IndentationError): 694 """ Improper mixture of spaces and tabs. """ 695 def __init__(self, *args, **kwargs): # real signature unknown 696 pass 697 698 699 class TimeoutError(OSError): 700 """ Timeout expired. """ 701 def __init__(self, *args, **kwargs): # real signature unknown 702 pass 703 704 705 class tuple(object): 706 """ 707 tuple() -> empty tuple 708 tuple(iterable) -> tuple initialized from iterable's items 709 710 If the argument is a tuple, the return value is the same object. 711 """ 712 def count(self, value): # real signature unknown; restored from __doc__ 713 """ T.count(value) -> integer -- return number of occurrences of value """ 714 return 0 715 716 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 717 """ 718 T.index(value, [start, [stop]]) -> integer -- return first index of value. 719 Raises ValueError if the value is not present. 720 """ 721 return 0 722 723 def __add__(self, *args, **kwargs): # real signature unknown 724 """ Return self+value. """ 725 pass 726 727 def __contains__(self, *args, **kwargs): # real signature unknown 728 """ Return key in self. """ 729 pass 730 731 def __eq__(self, *args, **kwargs): # real signature unknown 732 """ Return self==value. """ 733 pass 734 735 def __getattribute__(self, *args, **kwargs): # real signature unknown 736 """ Return getattr(self, name). """ 737 pass 738 739 def __getitem__(self, *args, **kwargs): # real signature unknown 740 """ Return self[key]. """ 741 pass 742 743 def __getnewargs__(self, *args, **kwargs): # real signature unknown 744 pass 745 746 def __ge__(self, *args, **kwargs): # real signature unknown 747 """ Return self>=value. """ 748 pass 749 750 def __gt__(self, *args, **kwargs): # real signature unknown 751 """ Return self>value. """ 752 pass 753 754 def __hash__(self, *args, **kwargs): # real signature unknown 755 """ Return hash(self). """ 756 pass 757 758 def __init__(self, seq=()): # known special case of tuple.__init__ 759 """ 760 tuple() -> empty tuple 761 tuple(iterable) -> tuple initialized from iterable's items 762 763 If the argument is a tuple, the return value is the same object. 764 # (copied from class doc) 765 """ 766 pass 767 768 def __iter__(self, *args, **kwargs): # real signature unknown 769 """ Implement iter(self). """ 770 pass 771 772 def __len__(self, *args, **kwargs): # real signature unknown 773 """ Return len(self). """ 774 pass 775 776 def __le__(self, *args, **kwargs): # real signature unknown 777 """ Return self<=value. """ 778 pass 779 780 def __lt__(self, *args, **kwargs): # real signature unknown 781 """ Return self<value. """ 782 pass 783 784 def __mul__(self, *args, **kwargs): # real signature unknown 785 """ Return self*value.n """ 786 pass 787 788 @staticmethod # known case of __new__ 789 def __new__(*args, **kwargs): # real signature unknown 790 """ Create and return a new object. See help(type) for accurate signature. """ 791 pass 792 793 def __ne__(self, *args, **kwargs): # real signature unknown 794 """ Return self!=value. """ 795 pass 796 797 def __repr__(self, *args, **kwargs): # real signature unknown 798 """ Return repr(self). """ 799 pass 800 801 def __rmul__(self, *args, **kwargs): # real signature unknown 802 """ Return self*value. """ 803 pass 804 805 806 class type(object): 807 """ 808 type(object_or_name, bases, dict) 809 type(object) -> the object's type 810 type(name, bases, dict) -> a new type 811 """ 812 def mro(self): # real signature unknown; restored from __doc__ 813 """ 814 mro() -> list 815 return a type's method resolution order 816 """ 817 return [] 818 819 def __call__(self, *args, **kwargs): # real signature unknown 820 """ Call self as a function. """ 821 pass 822 823 def __delattr__(self, *args, **kwargs): # real signature unknown 824 """ Implement delattr(self, name). """ 825 pass 826 827 def __dir__(self): # real signature unknown; restored from __doc__ 828 """ 829 __dir__() -> list 830 specialized __dir__ implementation for types 831 """ 832 return [] 833 834 def __getattribute__(self, *args, **kwargs): # real signature unknown 835 """ Return getattr(self, name). """ 836 pass 837 838 def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__ 839 """ 840 type(object_or_name, bases, dict) 841 type(object) -> the object's type 842 type(name, bases, dict) -> a new type 843 # (copied from class doc) 844 """ 845 pass 846 847 def __instancecheck__(self): # real signature unknown; restored from __doc__ 848 """ 849 __instancecheck__() -> bool 850 check if an object is an instance 851 """ 852 return False 853 854 @staticmethod # known case of __new__ 855 def __new__(*args, **kwargs): # real signature unknown 856 """ Create and return a new object. See help(type) for accurate signature. """ 857 pass 858 859 def __prepare__(self): # real signature unknown; restored from __doc__ 860 """ 861 __prepare__() -> dict 862 used to create the namespace for the class statement 863 """ 864 return {} 865 866 def __repr__(self, *args, **kwargs): # real signature unknown 867 """ Return repr(self). """ 868 pass 869 870 def __setattr__(self, *args, **kwargs): # real signature unknown 871 """ Implement setattr(self, name, value). """ 872 pass 873 874 def __sizeof__(self): # real signature unknown; restored from __doc__ 875 """ 876 __sizeof__() -> int 877 return memory consumption of the type object 878 """ 879 return 0 880 881 def __subclasscheck__(self): # real signature unknown; restored from __doc__ 882 """ 883 __subclasscheck__() -> bool 884 check if a class is a subclass 885 """ 886 return False 887 888 def __subclasses__(self): # real signature unknown; restored from __doc__ 889 """ __subclasses__() -> list of immediate subclasses """ 890 return [] 891 892 __abstractmethods__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 893 894 895 __bases__ = ( 896 object, 897 ) 898 __base__ = object 899 __basicsize__ = 864 900 __dictoffset__ = 264 901 __dict__ = None # (!) real value is '' 902 __flags__ = -2146675712 903 __itemsize__ = 40 904 __mro__ = ( 905 None, # (!) forward: type, real value is '' 906 object, 907 ) 908 __name__ = 'type' 909 __qualname__ = 'type' 910 __text_signature__ = None 911 __weakrefoffset__ = 368 912 913 914 class TypeError(Exception): 915 """ Inappropriate argument type. """ 916 def __init__(self, *args, **kwargs): # real signature unknown 917 pass 918 919 @staticmethod # known case of __new__ 920 def __new__(*args, **kwargs): # real signature unknown 921 """ Create and return a new object. See help(type) for accurate signature. """ 922 pass 923 924 925 class UnboundLocalError(NameError): 926 """ Local name referenced but not bound to a value. """ 927 def __init__(self, *args, **kwargs): # real signature unknown 928 pass 929 930 @staticmethod # known case of __new__ 931 def __new__(*args, **kwargs): # real signature unknown 932 """ Create and return a new object. See help(type) for accurate signature. """ 933 pass 934 935 936 class ValueError(Exception): 937 """ Inappropriate argument value (of correct type). """ 938 def __init__(self, *args, **kwargs): # real signature unknown 939 pass 940 941 @staticmethod # known case of __new__ 942 def __new__(*args, **kwargs): # real signature unknown 943 """ Create and return a new object. See help(type) for accurate signature. """ 944 pass 945 946 947 class UnicodeError(ValueError): 948 """ Unicode related error. """ 949 def __init__(self, *args, **kwargs): # real signature unknown 950 pass 951 952 @staticmethod # known case of __new__ 953 def __new__(*args, **kwargs): # real signature unknown 954 """ Create and return a new object. See help(type) for accurate signature. """ 955 pass 956 957 958 class UnicodeDecodeError(UnicodeError): 959 """ Unicode decoding error. """ 960 def __init__(self, *args, **kwargs): # real signature unknown 961 pass 962 963 @staticmethod # known case of __new__ 964 def __new__(*args, **kwargs): # real signature unknown 965 """ Create and return a new object. See help(type) for accurate signature. """ 966 pass 967 968 def __str__(self, *args, **kwargs): # real signature unknown 969 """ Return str(self). """ 970 pass 971 972 encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 973 """exception encoding""" 974 975 end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 976 """exception end""" 977 978 object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 979 """exception object""" 980 981 reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 982 """exception reason""" 983 984 start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 985 """exception start""" 986 987 988 989 class UnicodeEncodeError(UnicodeError): 990 """ Unicode encoding error. """ 991 def __init__(self, *args, **kwargs): # real signature unknown 992 pass 993 994 @staticmethod # known case of __new__ 995 def __new__(*args, **kwargs): # real signature unknown 996 """ Create and return a new object. See help(type) for accurate signature. """ 997 pass 998 999 def __str__(self, *args, **kwargs): # real signature unknown 1000 """ Return str(self). """ 1001 pass 1002 1003 encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 1004 """exception encoding""" 1005 1006 end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 1007 """exception end""" 1008 1009 object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 1010 """exception object""" 1011 1012 reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 1013 """exception reason""" 1014 1015 start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 1016 """exception start"""
随堂练习
#_contains__ name = "huyakun" #result = name.__contains__('hu') #__contains__相当于 in result= name in ('hu') print (result) >>> True #返回值都一样 #__getattribute_ 反射的时候用到 #center name = 'huyakun' result = name.center(20,'*')#内容居中,width:总长度;fillchar:空白处填充内容,默认无 print(result) >>>******huyakun******* #count 子序列个数 name = 'dfdfdsfdsfdsfjdsogdiosghdiojgiodgiodg' result =name.count('df'#寻找这个字符在字符串中共出现几次 #result = name.count('f',1,12)#可以加索引值来删选需要的信息 print(result) #encode 编码,针对unicod name = '胡亚坤' result = name.encode('gbk')#转换过程是:utf-8转unicod再转gbk print(result) >>>b'\xba\xfa\xd1\xc7\xc0\xa4' # endswith 是否以 xxx 结束 """ name = 'huyakun' result = name.endswith('n') 或者result=name.endswith('y',0,3) print(result) >>>True #expandtabs将tab转换成空格 name = 'hu\tyakun'#\t等于tabs result = name.expandtabs() print(result) #find 寻找子序列位置,如果没找到,返回 -1 name = 'huyakun' result = name.find('un') #result = name.index('un')#寻找子序列位置,如果没找到,返回错误提示 print(result) #format 字符串格式化,动态参数 name = 'huyakun {0} as {1}' result = name.format('age','sb') print(result) name = 'huyakun {age} as {sb}' result = name.format(age='26',sb ="huya")#字符串拼接 print(result) #jion 连接 list = ['h','u','y','a','k','u','n'] result = "".join(list) #result ="-".join(list)#可以在前面加内容 print(result) #.partition 分割,前,中,后三部分 name = 'huyakunage26' result = name.partition('age') print(result #replace 替换 name ='huyakun' result = name.replace('u','o') #result = name.replace('u','o'1)#替换值这个字符串的出现的第一个u print(result) #splitlines 分割换行等同于\n name = """ aa bb cc """ #result = name.splitlines() result = name.split("\n") print(result)
三、列表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
#append li = [1,2,3] #print(li) li.append(1) print(li) #extend 列表的扩展等同于新增 li = ([1,2,3]) result = li.extend([22,88,]) print(li) #insert 在指定索引值下面插入 li = ([1,2,3]) li.insert(0,'huyaun')#指定插入在索引值下或下标 print(li) #pop 去掉一个值 li = ([1,2,3]) ret = li.pop(0)#去列表里面取一个值 print(ret) #remove 指定删除 li = [1,2,3] #print(li) li.remove(3) print(li) #reverse 反转 li = [1,2,3,88,99,77,98] #print(li) li.reverse() print(li)
四、元组
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 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 __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, seq=()): # known special case of tuple.__init__ """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. # (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 __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass
tu = (1,2,3,4,) tu = list(tu)#元组转列表 print (tu) i = [1,2,3,4,] tu = tuple(i)#列表转元组 print(tu)
五、字典
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def items(self): # real signature unknown; restored from __doc__ """ D.items() -> a set-like object providing a view on D's items """ pass def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> a set-like object providing a view on D's keys """ pass def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ D.values() -> an object providing a view on D's values """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ True if D has a key k, else False. """ 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 __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (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 @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 __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None
随堂练习
#dic = {'k1':'v1','k2':'v2'} dic = dict(k1='v1',k2='v2') new_dic = dic.fromkeys(['k1','k2','k3'],'v1') print(new_dic) #当如下字典中不含有‘k3’时会报错如何解决这种报错使用get dic = {'k1':'v1','k2':'v2'} print(dic['k1']) print(dic['k2']) #print(dic['k3']) ------------------ print(dic.get('k3','huyakun'))#当k3不存在时也可以指定返回某一个值 #.keys,values,.items dic = {'k1':'v1','k2':'v2'} print (dic.keys())#获取所有的键 print (dic.values())#获取所有的值 print (dic.items())#获取所有的键值对 for k in dic.keys(): print(k) for v in dic.values(): print(v) for k,v in dic.items(): print(k,v) #pop 取走拿走 dic = {'k1':'v1','k2':'v2'} dic.pop('k1') print(dic) dic.pop('k1') print(dic) #popitem 不常用并且取值不确定,字典无序 dic = {'k1':'v1','k2':'v2'} dic.popitem() print(dic) #update 更新 dic = {'k1':'v1','k2':'v2'} dic.update({'k3':123}) print(dic) 当更新以后还是跟以前一样说明:更新值被返回来啦 #ret =dic.updat{'k3':'123'} print(ret)
练习:元素分类
有如下值集合 [
11
,
22
,
33
,
44
,
55
,
66
,
77
,
88
,
99
,
90.
..],将所有大于
66
的值保存至字典的第一个key中,将小于
66
的值保存至第二个key的值中。
即: {
'k1'
: 大于
66
,
'k2'
: 小于
66
}
1 #实现方法一: 2 all_list =[11,22,33,44,55,66,77,88,99,90,] 3 dic = {} 4 l1 = [] 5 l2 = [] 6 for i in all_list: 7 if i> 66: 8 l1.append(i) 9 else: 10 l2.append(i) 11 dic['k1'] = l1 12 dic['k2'] = l2 13 print(l1) 14 print(l2)