Python基本数据类型
- 数字、布尔值、字符串、列表、元组、字典、set集合
一、数字(number)
int(整型)
1 a = 102 b = a3 b = 884 5 print(a) #结果:106 print(b) #结果:888
1 var1=3.142 var2=53 var3=int(var1)4 var4=float(var2)5 6 print(var3,var4)
1 abs(x) 返回数字的绝对值,如abs(-10) 返回 10 2 # ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5 3 # cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1 4 # exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 5 # fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0 6 # floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4 7 # log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 8 # log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0 9 # max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。10 # min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。11 # modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。12 # pow(x, y) x**y 运算后的值。13 # round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。14 # sqrt(x) 返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回 2+0j15 16 PY内置数学函数
1 class int(object): 2 """ 3 int(x=0) -> integer 4 int(x, base=10) -> integer 5 6 Convert a number or string to an integer, or return 0 if no arguments 7 are given. If x is a number, return x.__int__(). For floating point 8 numbers, this truncates towards zero. 9 10 If x is not a number or if base is given, then x must be a string, 11 bytes, or bytearray instance representing an integer literal in the 12 given base. The literal can be preceded by '+' or '-' and be surrounded 13 by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. 14 Base 0 means to interpret the base from the string as an integer literal. 15 >>> int('0b100', base=0) 16 """ 17 def bit_length(self): # real signature unknown; restored from __doc__ 18 """ 19 int.bit_length() -> int 20 21 Number of bits necessary to represent self in binary. 22 """ 23 """ 24 表示该数字返回时占用的最少位数 25 26 >>> (951).bit_length() 27 10 28 """ 29 return 0 30 31 def conjugate(self, *args, **kwargs): # real signature unknown 32 """ Returns self, the complex conjugate of any int.""" 33 34 """ 35 返回该复数的共轭复数 36 37 #返回复数的共轭复数 38 >>> (95 + 11j).conjugate() 39 (95-11j) 40 #返回复数的实数部分 41 >>> (95 + 11j).real 42 95.0 43 #返回复数的虚数部分 44 >>> (95 + 11j).imag 45 11.0 46 """ 47 pass 48 49 @classmethod # known case 50 def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 51 """ 52 int.from_bytes(bytes, byteorder, *, signed=False) -> int 53 54 Return the integer represented by the given array of bytes. 55 56 The bytes argument must be a bytes-like object (e.g. bytes or bytearray). 57 58 The byteorder argument determines the byte order used to represent the 59 integer. If byteorder is 'big', the most significant byte is at the 60 beginning of the byte array. If byteorder is 'little', the most 61 significant byte is at the end of the byte array. To request the native 62 byte order of the host system, use `sys.byteorder' as the byte order value. 63 64 The signed keyword-only argument indicates whether two's complement is 65 used to represent the integer. 66 """ 67 """ 68 这个方法是在Python3.2的时候加入的,python官方给出了下面几个例子: 69 >>> int.from_bytes(b'\x00\x10', byteorder='big') 70 >>> int.from_bytes(b'\x00\x10', byteorder='little') 71 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) 72 -1024 73 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 74 >>> int.from_bytes([255, 0, 0], byteorder='big') 75 """ 76 pass 77 78 def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 79 """ 80 int.to_bytes(length, byteorder, *, signed=False) -> bytes 81 82 Return an array of bytes representing an integer. 83 84 The integer is represented using length bytes. An OverflowError is 85 raised if the integer is not representable with the given number of 86 bytes. 87 88 The byteorder argument determines the byte order used to represent the 89 integer. If byteorder is 'big', the most significant byte is at the 90 beginning of the byte array. If byteorder is 'little', the most 91 significant byte is at the end of the byte array. To request the native 92 byte order of the host system, use `sys.byteorder' as the byte order value. 93 94 The signed keyword-only argument determines whether two's complement is 95 used to represent the integer. If signed is False and a negative integer 96 is given, an OverflowError is raised. 97 """ 98 """ 99 python官方给出了下面几个例子:100 >>> (1024).to_bytes(2, byteorder='big')101 b'\x04\x00'102 >>> (1024).to_bytes(10, byteorder='big')103 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'104 >>> (-1024).to_bytes(10, byteorder='big', signed=True)105 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'106 >>> x = 1000107 >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')108 b'\xe8\x03'109 """110 pass111 112 def __abs__(self, *args, **kwargs): # real signature unknown113 """ abs(self)"""114 115 """116 返回一个绝对值117 118 >>> (95).__abs__()119 -95120 >>> (-95).__abs__()121 95122 """123 pass124 125 126 def __add__(self, *args, **kwargs): # real signature unknown127 """ Return self+value."""128 129 """130 加法,也可区分数字和字符串131 132 >>> (95).__add__(1)133 96134 >>> (95).__add__("1")135 NotImplemented136 >>>137 """138 pass139 140 def __and__(self, *args, **kwargs): # real signature unknown141 """ Return self&value."""142 pass143 144 def __bool__(self, *args, **kwargs): # real signature unknown145 """ self != 0 """146 147 """148 判断一个整数对象是否为0,如果为0,则返回False,如果不为0,则返回True149 150 >>> (95).__bool__()151 True152 >>> (0).__bool__()153 False154 """155 pass156 157 def __ceil__(self, *args, **kwargs): # real signature unknown158 """ Ceiling of an Integral returns itself. """159 pass160 161 def __divmod__(self, *args, **kwargs): # real signature unknown162 """ Return divmod(self, value). """163 """164 返回一个元组,第一个元素为商,第二个元素为余数165 166 >>> (9).__divmod__(5)167 (1, 4)168 """169 pass170 171 def __eq__(self, *args, **kwargs): # real signature unknown172 """ Return self==value. """173 """174 判断两个值是否相等175 176 >>> (95).__eq__(95)177 True178 >>> (95).__eq__(9)179 False180 """181 pass182 183 def __float__(self, *args, **kwargs): # real signature unknown184 """ float(self) """185 """186 将一个整数转换成浮点型187 188 >>> (95).__float__()189 95.0190 """191 pass192 193 def __floordiv__(self, *args, **kwargs): # real signature unknown194 """ Return self//value. """195 """196 整除,保留结果的整数部分197 198 >>> (95).__floordiv__(9)199 10200 """201 pass202 203 def __floor__(self, *args, **kwargs): # real signature unknown204 """ Flooring an Integral returns itself. """205 """206 返回本身207 208 >>> (95).__floor__()209 95210 """211 pass212 213 def __format__(self, *args, **kwargs): # real signature unknown214 """215 转换对象的类型216 217 >>> (95).__format__('f')218 '95.000000'219 >>> (95).__format__('b')220 '1011111'221 """222 pass223 224 225 def __getattribute__(self, *args, **kwargs): # real signature unknown226 """ Return getattr(self, name). """227 """228 判断这个类中是否包含这个属性,如果包含则打印出值,如果不包含,就报错了229 230 >>> (95).__getattribute__('__abs__')231232 >>> (95).__getattribute__('__aaa__')233 Traceback (most recent call last):234 File " ", line 1, in 235 AttributeError: 'int' object has no attribute '__aaa__'236 """237 pass238 239 def __getnewargs__(self, *args, **kwargs): # real signature unknown240 pass241 242 def __ge__(self, *args, **kwargs): # real signature unknown243 """ Return self>=value. """244 """245 判断是否大于等于246 247 >>> (95).__ge__(9)248 True249 >>> (95).__ge__(99)250 False251 """252 pass253 254 def __gt__(self, *args, **kwargs): # real signature unknown255 """ Return self>value. """256 """257 判断是否大于258 259 >>> (95).__gt__(9)260 True261 >>> (95).__gt__(99)262 False263 """264 pass265 266 def __hash__(self, *args, **kwargs): # real signature unknown267 """ Return hash(self). """268 """269 计算哈希值,整数返回本身270 271 >>> (95).__hash__()272 95273 >>> (95.95).__hash__()274 2190550858753015903275 """276 pass277 278 def __index__(self, *args, **kwargs): # real signature unknown279 """ Return self converted to an integer, if self is suitable for use as an index into a list. """280 pass281 282 def __init__(self, x, base=10): # known special case of int.__init__283 """284 这个是一个类的初始化方法,当int类被实例化的时候,这个方法默认就会被执行285 """286 """287 int(x=0) -> integer288 int(x, base=10) -> integer289 290 Convert a number or string to an integer, or return 0 if no arguments291 are given. If x is a number, return x.__int__(). For floating point292 numbers, this truncates towards zero.293 294 If x is not a number or if base is given, then x must be a string,295 bytes, or bytearray instance representing an integer literal in the296 given base. The literal can be preceded by '+' or '-' and be surrounded297 by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.298 Base 0 means to interpret the base from the string as an integer literal.299 >>> int('0b100', base=0)300 # (copied from class doc)301 """ 302 pass303 304 def __int__(self, *args, **kwargs): # real signature unknown305 """ int(self) """306 """307 转换为整型308 309 >>> (9.5).__int__()310 9311 """312 pass313 314 315 def __invert__(self, *args, **kwargs): # real signature unknown316 """ ~self """317 318 pass319 320 def __le__(self, *args, **kwargs): # real signature unknown321 """ Return self<=value. """322 """323 判断是否小于等于324 325 >>> (95).__le__(99)326 True327 >>> (95).__le__(9)328 False329 """330 pass331 332 def __lshift__(self, *args, **kwargs): # real signature unknown333 """ Return self< >> bin(95)338 '0b1011111'339 >>> a = (95).__lshift__(2)340 >>> bin(a)341 '0b101111100'342 >>> 343 """344 pass345 346 def __lt__(self, *args, **kwargs): # real signature unknown347 """ Return self >> (95).__lt__(9)352 False353 >>> (95).__lt__(99)354 True355 """356 pass357 358 def __mod__(self, *args, **kwargs): # real signature unknown359 """ Return self%value. """360 """361 取模 %362 363 >>> (95).__mod__(9)364 """365 pass366 367 def __mul__(self, *args, **kwargs): # real signature unknown368 """ Return self*value. """369 """370 乘法 *371 372 >>> (95).__mul__(10)373 """374 pass375 376 def __neg__(self, *args, **kwargs): # real signature unknown377 """ -self """378 """379 将正数变为负数,将负数变为正数380 381 >>> (95).__neg__()382 -95383 >>> (-95).__neg__()384 95385 """386 pass387 388 @staticmethod # known case of __new__389 def __new__(*args, **kwargs): # real signature unknown390 """ Create and return a new object. See help(type) for accurate signature. """391 pass392 393 def __ne__(self, *args, **kwargs): # real signature unknown394 """ Return self!=value. """395 """396 不等于397 398 >>> (95).__ne__(9)399 True400 >>> (95).__ne__(95)401 False402 """403 pass404 405 def __or__(self, *args, **kwargs): # real signature unknown406 """ Return self|value. """407 """408 二进制或的关系,只要有一个为真,就为真409 410 >>> a = 4411 >>> b = 0412 >>> a.__or__(b) # a --> 00000100 b --> 00000000413 >>> b = 1 # b --> 00000001414 >>> a.__or__(b)415 """416 pass417 418 def __pos__(self, *args, **kwargs): # real signature unknown419 """ +self """420 pass421 422 def __pow__(self, *args, **kwargs): # real signature unknown423 """ Return pow(self, value, mod). """424 """425 幂426 427 >>> (2).__pow__(10)428 1024429 """ 430 pass431 432 def __radd__(self, *args, **kwargs): # real signatre unknown433 """ Return value+self. """434 """435 加法,将value放在前面436 437 >>> a.__radd__(b) # 相当于 b+a 438 """439 pass440 441 def __rand__(self, *args, **kwargs): # real signature unknown442 """ Return value&self. """443 """444 二进制与的关系,两个都为真,才为真,有一个为假,就为假445 """446 pass447 448 def __rdivmod__(self, *args, **kwargs): # real signature unknown449 """ Return divmod(value, self). """450 pass451 452 def __repr__(self, *args, **kwargs): # real signature unknown453 """ Return repr(self). """454 pass455 456 def __rfloordiv__(self, *args, **kwargs): # real signature unknown457 """ Return value//self. """458 pass459 460 def __rlshift__(self, *args, **kwargs): # real signature unknown461 """ Return value< >self. """489 pass490 491 def __rshift__(self, *args, **kwargs): # real signature unknown492 """ Return self>>value. """493 pass494 495 def __rsub__(self, *args, **kwargs): # real signature unknown496 """ Return value-self. """497 pass498 499 def __rtruediv__(self, *args, **kwargs): # real signature unknown500 """ Return value/self. """501 pass502 503 def __rxor__(self, *args, **kwargs): # real signature unknown504 """ Return value^self. """505 pass506 507 def __sizeof__(self, *args, **kwargs): # real signature unknown508 """ Returns size in memory, in bytes """509 """510 在内存中占多少个字节511 512 >>> a = 95513 >>> a.__sizeof__()514 28515 """516 pass517 518 def __str__(self, *args, **kwargs): # real signature unknown519 """ Return str(self). """520 """521 将一个正数转为字符串522 523 >>> a = 95 524 >>> a = a.__str__()525 >>> print(type(a))526 527 """528 pass529 530 def __sub__(self, *args, **kwargs): # real signature unknown531 """ Return self-value. """532 """533 减法运算534 535 >>> (95).__sub__(5)536 90537 """538 pass539 540 def __truediv__(self, *args, **kwargs): # real signature unknown541 """ Return self/value. """542 """543 除法运算544 545 >>> (95).__truediv__(5)546 19.0547 """548 pass549 550 def __trunc__(self, *args, **kwargs): # real signature unknown551 """ Truncating an Integral returns itself. """552 """553 返回一个对象的整数部分554 555 >>> (95.95).__trunc__()556 95557 """558 pass559 def __xor__(self, *args, **kwargs): # real signature unknown560 """ Return self^value. """561 """562 将对象与值进行二进制的或运算,一个为真,就为真563 564 >>> a = 4565 >>> b = 1566 >>> a.__xor__(b)567 >>> c = 0568 >>> a.__xor__(c)569 """570 571 pass572 573 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default574 """ 分母 = 1 """575 """the denominator of a rational number in lowest terms"""576 577 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default578 """ 虚数 """579 """the imaginary part of a complex number"""580 581 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default582 """ 分子 = 数字大小 """583 """the numerator of a rational number in lowest terms"""584 585 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default586 """ 实属 """587 """the real part of a complex number"""
二、字符串类型(string)
字符串是以单引号、双引号括起来的任意文本,比如:'abc'、'123'等。
注意:''
或""
本身只是一种表示方式,不是字符串的一部分,因此,字符串'abc'
只有a
,b
,c
这3个字符。如果'
本身也是一个字符,那就可以用""
括起来,比如"I'm OK"
包含的字符是I
,'
,m
,空格,O
,K
这6个字符。
2.1、创建字符串
1 cha1 = 'Hello World!'2 cha2 = "Python chanper"
2.1.1、对应的操作
1 # 1 * 重复输出字符串 2 print('hello'*2) 3 4 # 2 [] ,[:] 通过索引获取字符串中字符,这里和列表的切片操作是相同的,具体内容见列表 5 print('helloworld'[2:]) 6 7 # 3 in 成员运算符 - 如果字符串中包含给定的字符返回 True 8 print('el' in 'hello') 9 10 # 4 % 格式字符串11 print('alex is a good teacher')12 print('%s is a good teacher'%'alex')13 14 15 # 5 + 字符串拼接16 a='123'17 b='abc'18 c='789'19 d1=a+b+c20 print(d1)21 # +效率低,该用join22 d2=''.join([a,b,c])23 print(d2)
2.1.2、python的内置方法
1 # string.capitalize() 把字符串的第一个字符大写 2 # string.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串 3 # string.count(str, beg=0, end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 4 # string.decode(encoding='UTF-8', errors='strict') 以 encoding 指定的编码格式解码 string,如果出错默认报一个 ValueError 的 异 常 , 除 非 errors 指 定 的 是 'ignore' 或 者'replace' 5 # string.encode(encoding='UTF-8', errors='strict') 以 encoding 指定的编码格式编码 string,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace' 6 # string.endswith(obj, beg=0, end=len(string)) 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False. 7 # string.expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8。 8 # string.find(str, beg=0, end=len(string)) 检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 9 # string.index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在 string中会报一个异常.10 # string.isalnum() 如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False11 # string.isalpha() 如果 string 至少有一个字符并且所有字符都是字母则返回 True,否则返回 False12 # string.isdecimal() 如果 string 只包含十进制数字则返回 True 否则返回 False.13 # string.isdigit() 如果 string 只包含数字则返回 True 否则返回 False.14 # string.islower() 如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False15 # string.isnumeric() 如果 string 中只包含数字字符,则返回 True,否则返回 False16 # string.isspace() 如果 string 中只包含空格,则返回 True,否则返回 False.17 # string.istitle() 如果 string 是标题化的(见 title())则返回 True,否则返回 False18 # string.isupper() 如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False19 # string.join(seq) 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串20 # string.ljust(width) 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串21 # string.lower() 转换 string 中所有大写字符为小写.22 # string.lstrip() 截掉 string 左边的空格23 # string.maketrans(intab, outtab]) maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。24 # max(str) 返回字符串 str 中最大的字母。25 # min(str) 返回字符串 str 中最小的字母。26 # string.partition(str) 有点像 find()和 split()的结合体,从 str 出现的第一个位置起,把 字 符 串 string 分 成 一 个 3 元 素 的 元 组 (string_pre_str,str,string_post_str),如果 string 中不包含str 则 string_pre_str == string.27 # string.replace(str1, str2, num=string.count(str1)) 把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次.28 # string.rfind(str, beg=0,end=len(string) ) 类似于 find()函数,不过是从右边开始查找.29 # string.rindex( str, beg=0,end=len(string)) 类似于 index(),不过是从右边开始.30 # string.rjust(width) 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串31 # string.rpartition(str) 类似于 partition()函数,不过是从右边开始查找.32 # string.rstrip() 删除 string 字符串末尾的空格.33 # string.split(str="", num=string.count(str)) 以 str 为分隔符切片 string,如果 num有指定值,则仅分隔 num 个子字符串34 # string.splitlines(num=string.count('\n')) 按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定则仅切片 num 个行.35 # string.startswith(obj, beg=0,end=len(string)) 检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查.36 # string.strip([obj]) 在 string 上执行 lstrip()和 rstrip()37 # string.swapcase() 翻转 string 中的大小写38 # string.title() 返回"标题化"的 string,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())39 # string.translate(str, del="") 根据 str 给出的表(包含 256 个字符)转换 string 的字符,要过滤掉的字符放到 del 参数中40 # string.upper() 转换 string 中的小写字母为大写
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 首字母变大写 17 name = "nick is good, Today is nice day." 18 a = name.capitalize() 19 print(a) 20 """ 21 S.capitalize() -> str 22 23 Return a capitalized version of S, i.e. make the first character 24 have upper case and the rest lower case. 25 """ 26 return "" 27 28 def casefold(self): # real signature unknown; restored from __doc__ 29 """ 30 首字母变小写 31 name = "Nick is good, Today is nice day. 32 a =name.casefold() 33 print(a) 34 """ 35 S.casefold() -> str 36 37 Return a version of S suitable for caseless comparisons. 38 """ 39 return "" 40 41 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ 42 """ 43 内容居中,width:总长度;fillchar:空白处填充内容,默认无。 44 name = "Nick is good, Today is nice day. 45 a = name.center(60,'$') 46 print(a) 47 """ 48 S.center(width[, fillchar]) -> str 49 Return S centered in a string of length width. Padding is 50 done using the specified fill character (default is a space) 51 """ 52 return "" 53 54 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 55 """ 56 子序列个数,0到26中n出现了几次。 57 name = "nck is good, Today is nice day. 58 a = name.count("n",0,26) 59 print(a) 60 """ 61 S.count(sub[, start[, end]]) -> int 62 63 Return the number of non-overlapping occurrences of substring sub in 64 string S[start:end]. Optional arguments start and end are 65 interpreted as in slice notation. 66 """ 67 return 0 68 69 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ 70 """ 71 """ 72 编码,针对unicode. 73 temp = "烧饼 74 temp.encode("unicode") 75 """ 76 S.encode(encoding='utf-8', errors='strict') -> bytes 77 78 Encode S using the codec registered for encoding. Default encoding 79 is 'utf-8'. errors may be given to set a different error 80 handling scheme. Default is 'strict' meaning that encoding errors raise 81 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 82 'xmlcharrefreplace' as well as any other name registered with 83 codecs.register_error that can handle UnicodeEncodeErrors. 84 """ 85 return b"" 86 87 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ 88 """ 89 """ 90 是否以XX结束,0到4是否以k结尾 91 name = "nck is good, Today is nice day. 92 a = name.endswith("k",0,4) 93 print(a) 94 """ 95 S.endswith(suffix[, start[, end]]) -> bool 96 97 Return True if S ends with the specified suffix, False otherwise. 98 With optional start, test S beginning at that position. 99 With optional end, stop comparing S at that position.100 suffix can also be a tuple of strings to try.101 """102 return False103 104 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__105 """106 """ 107 将tab转换成空格,默认一个tab转换成8个空格 108 a = n.expandtabs()109 b = n.expandtabs(16)110 print(a)111 print(b)112 """113 S.expandtabs(tabsize=8) -> str114 115 Return a copy of S where all tab characters are expanded using spaces.116 If tabsize is not given, a tab size of 8 characters is assumed.117 """118 return ""119 120 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__121 """122 """ 123 寻找子序列位置,如果没找到,返回 -1。124 name = "nck is good, Today is nice day. "125 a = name.find("nickk")126 print(a)127 """128 S.find(sub[, start[, end]]) -> int129 130 Return the lowest index in S where substring sub is found,131 such that sub is contained within S[start:end]. Optional132 arguments start and end are interpreted as in slice notation.133 134 Return -1 on failure.135 """136 return 0137 138 def format(self, *args, **kwargs): # known special case of str.format139 """140 """ 141 字符串格式化,动态参数142 name = "nck is good, Today is nice day. "143 a = name.format()144 print(a)145 """146 S.format(*args, **kwargs) -> str147 148 Return a formatted version of S, using substitutions from args and kwargs.149 The substitutions are identified by braces ('{' and '}').150 """151 pass152 153 def format_map(self, mapping): # real signature unknown; restored from __doc__154 """155 """156 dict = { 'Foo': 54.23345}157 fmt = "Foo = {Foo:.3f}"158 result = fmt.format_map(dict)159 print(result) #Foo = 54.233160 """161 S.format_map(mapping) -> str162 163 Return a formatted version of S, using substitutions from mapping.164 The substitutions are identified by braces ('{' and '}').165 """166 return ""167 168 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__169 """170 """171 #子序列位置,如果没有找到就报错172 name = "nck is good, Today is nice day. "173 a = name.index("nick")174 print(a)175 """176 S.index(sub[, start[, end]]) -> int177 178 Like S.find() but raise ValueError when the substring is not found.179 """180 return 0181 182 def isalnum(self): # real signature unknown; restored from __doc__183 """184 """ 185 是否是字母和数字186 name = "nck is good, Today is nice day. "187 a = name.isalnum()188 print(a)189 """190 S.isalnum() -> bool191 192 Return True if all characters in S are alphanumeric193 and there is at least one character in S, False otherwise.194 """195 return False196 197 def isalpha(self): # real signature unknown; restored from __doc__198 """199 """ 200 是否是字母201 name = "nck is good, Today is nice day. "202 a = name.isalpha()203 print(a)204 """205 S.isalpha() -> bool206 207 Return True if all characters in S are alphabetic208 and there is at least one character in S, False otherwise.209 """210 return False211 212 def isdecimal(self): # real signature unknown; restored from __doc__213 """214 检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。215 """216 S.isdecimal() -> bool217 218 Return True if there are only decimal characters in S,219 False otherwise.220 """221 return False222 223 def isdigit(self): # real signature unknown; restored from __doc__224 """225 """ 226 是否是数字227 name = "nck is good, Today is nice day. "228 a = name.isdigit()229 print(a)230 """231 S.isdigit() -> bool232 233 Return True if all characters in S are digits234 and there is at least one character in S, False otherwise.235 """236 return False237 238 def isidentifier(self): # real signature unknown; restored from __doc__239 """240 """241 判断字符串是否可为合法的标识符242 """243 S.isidentifier() -> bool244 245 Return True if S is a valid identifier according246 to the language definition.247 248 Use keyword.iskeyword() to test for reserved identifiers249 such as "def" and "class".250 """251 return False252 253 def islower(self): # real signature unknown; restored from __doc__254 """255 """256 是否小写 257 name = "nck is good, Today is nice day. "258 a = name.islower()259 print(a)260 """261 S.islower() -> bool262 263 Return True if all cased characters in S are lowercase and there is264 at least one cased character in S, False otherwise.265 """266 return False267 268 def isnumeric(self): # real signature unknown; restored from __doc__269 """270 """271 检查是否只有数字字符组成的字符串272 name = "111111111111111”273 a = name.isnumeric()274 print(a)275 """276 S.isnumeric() -> bool277 278 Return True if there are only numeric characters in S,279 False otherwise.280 """281 return False282 283 def isprintable(self): # real signature unknown; restored from __doc__284 """285 """286 判断字符串中所有字符是否都属于可见字符287 name = "nck is good, Today is nice day. "288 a = name.isprintable()289 print(a)290 """291 S.isprintable() -> bool292 293 Return True if all characters in S are considered294 printable in repr() or S is empty, False otherwise.295 """296 return False297 298 def isspace(self): # real signature unknown; restored from __doc__299 """300 """301 字符串是否只由空格组成302 name = " "303 a = name.isspace()304 print(a)305 """306 S.isspace() -> bool307 308 Return True if all characters in S are whitespace309 and there is at least one character in S, False otherwise.310 """311 return False312 313 def istitle(self): # real signature unknown; restored from __doc__314 """315 """316 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写317 name = "Nick, Today."318 a = name.istitle()319 print(a)320 """321 """322 S.istitle() -> bool323 324 Return True if S is a titlecased string and there is at least one325 character in S, i.e. upper- and titlecase characters may only326 follow uncased characters and lowercase characters only cased ones.327 Return False otherwise.328 """329 return False330 331 def isupper(self): # real signature unknown; restored from __doc__332 """333 """334 检测字符串中所有的字母是否都为大写335 name = "NICK"336 a = name.isupper()337 print(a)338 """339 S.isupper() -> bool340 341 Return True if all cased characters in S are uppercase and there is342 at least one cased character in S, False otherwise.343 """344 return False345 346 def join(self, iterable): # real signature unknown; restored from __doc__347 """348 """ 349 连接两个字符串350 li = ["nick","serven"]351 a = "".join(li)352 b = "_".join(li)353 print(a)354 print(b)355 """356 S.join(iterable) -> str357 358 Return a string which is the concatenation of the strings in the359 iterable. The separator between elements is S.360 """361 return ""362 363 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__364 """365 """ 366 向左对齐,右侧填充367 name = "nck is good, Today is nice day. "368 a = name.ljust(66)369 print(a)370 """371 S.ljust(width[, fillchar]) -> str372 373 Return S left-justified in a Unicode string of length width. Padding is374 done using the specified fill character (default is a space).375 """376 return ""377 378 def lower(self): # real signature unknown; restored from __doc__379 """380 """ 381 容左对齐,右侧填充382 name = "NiNi"383 a = name.lower()384 print(a)385 """386 S.lower() -> str387 388 Return a copy of the string S converted to lowercase.389 """390 return ""391 392 def lstrip(self, chars=None): # real signature unknown; restored from __doc__393 """394 """ 移除左侧空白 """395 S.lstrip([chars]) -> str396 397 Return a copy of the string S with leading whitespace removed.398 If chars is given and not None, remove characters in chars instead.399 """400 return ""401 402 def maketrans(self, *args, **kwargs): # real signature unknown403 """404 """405 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。406 from string import maketrans407 intab = "aeiou"408 outtab = "12345"409 trantab = maketrans(intab, outtab)410 str = "this is string example....wow!!!";411 print str.translate(trantab);412 """413 Return a translation table usable for str.translate().414 415 If there is only one argument, it must be a dictionary mapping Unicode416 ordinals (integers) or characters to Unicode ordinals, strings or None.417 Character keys will be then converted to ordinals.418 If there are two arguments, they must be strings of equal length, and419 in the resulting dictionary, each character in x will be mapped to the420 character at the same position in y. If there is a third argument, it421 must be a string, whose characters will be mapped to None in the result.422 """423 pass424 425 def partition(self, sep): # real signature unknown; restored from __doc__426 """427 """ 428 分割,前,中,后三部分 429 name = "Nick is good, Today is nice day."430 a = name.partition("good")431 print(a)432 """433 S.partition(sep) -> (head, sep, tail)434 435 Search for the separator sep in S, and return the part before it,436 the separator itself, and the part after it. If the separator is not437 found, return S and two empty strings.438 """439 pass440 441 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__442 """443 """ 444 替换445 name = "Nick is good, Today is nice day."446 a = name.replace("good","man")447 print(a)448 """449 S.replace(old, new[, count]) -> str450 451 Return a copy of S with all occurrences of substring452 old replaced by new. If the optional argument count is453 given, only the first count occurrences are replaced.454 """455 return ""456 457 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__458 """459 """460 返回字符串最后一次出现的位置,如果没有匹配项则返回-1461 """462 S.rfind(sub[, start[, end]]) -> int463 464 Return the highest index in S where substring sub is found,465 such that sub is contained within S[start:end]. Optional466 arguments start and end are interpreted as in slice notation.467 468 Return -1 on failure.469 """470 return 0471 472 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__473 """474 """475 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常476 """477 S.rindex(sub[, start[, end]]) -> int478 479 Like S.rfind() but raise ValueError when the substring is not found.480 """481 return 0482 483 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__484 """485 """486 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串487 str = "this is string example....wow!!!"488 print(str.rjust(50, '$'))489 """490 S.rjust(width[, fillchar]) -> str491 492 Return S right-justified in a string of length width. Padding is493 done using the specified fill character (default is a space).494 """495 return ""496 497 def rpartition(self, sep): # real signature unknown; restored from __doc__498 """499 """500 根据指定的分隔符将字符串进行分割501 """502 S.rpartition(sep) -> (head, sep, tail)503 504 Search for the separator sep in S, starting at the end of S, and return505 the part before it, the separator itself, and the part after it. If the506 separator is not found, return two empty strings and S.507 """508 pass509 510 def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__511 """512 """513 指定分隔符对字符串进行切片514 name = "Nick is good, Today is nice day."515 a = name.rsplit("is")516 print(a)517 """518 S.rsplit(sep=None, maxsplit=-1) -> list of strings519 520 Return a list of the words in S, using sep as the521 delimiter string, starting at the end of the string and522 working to the front. If maxsplit is given, at most maxsplit523 splits are done. If sep is not specified, any whitespace string524 is a separator.525 """526 return []527 528 def rstrip(self, chars=None): # real signature unknown; restored from __doc__529 """530 """531 删除 string 字符串末尾的指定字符(默认为空格)532 """533 S.rstrip([chars]) -> str534 535 Return a copy of the string S with trailing whitespace removed.536 If chars is given and not None, remove characters in chars instead.537 """538 return ""539 540 def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__541 """542 """543 通过指定分隔符对字符串进行切片544 str = "Line1-abcdef \nLine2-abc \nLine4-abcd";545 print str.split( );546 print str.split(' ', 1 );547 """548 S.split(sep=None, maxsplit=-1) -> list of strings549 550 Return a list of the words in S, using sep as the551 delimiter string. If maxsplit is given, at most maxsplit552 splits are done. If sep is not specified or is None, any553 whitespace string is a separator and empty strings are554 removed from the result.555 """556 return []557 558 def splitlines(self, keepends=None): # real signature unknown; restored from __doc__559 """560 """561 按照行分隔,返回一个包含各行作为元素的列表562 """563 S.splitlines([keepends]) -> list of strings564 565 Return a list of the lines in S, breaking at line boundaries.566 Line breaks are not included in the resulting list unless keepends567 is given and true.568 """569 return []570 571 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__572 """573 """574 检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False575 """576 S.startswith(prefix[, start[, end]]) -> bool577 578 Return True if S starts with the specified prefix, False otherwise.579 With optional start, test S beginning at that position.580 With optional end, stop comparing S at that position.581 prefix can also be a tuple of strings to try.582 """583 return False584 585 def strip(self, chars=None): # real signature unknown; restored from __doc__586 """587 """588 用于移除字符串头尾指定的字符(默认为空格).589 """590 S.strip([chars]) -> str591 592 Return a copy of the string S with leading and trailing593 whitespace removed.594 If chars is given and not None, remove characters in chars instead.595 """596 return ""597 598 def swapcase(self): # real signature unknown; restored from __doc__599 """600 """601 用于对字符串的大小写字母进行转换602 """603 S.swapcase() -> str604 605 Return a copy of S with uppercase characters converted to lowercase606 and vice versa.607 """608 return ""609 610 def title(self): # real signature unknown; restored from __doc__611 """612 S.title() -> str613 614 Return a titlecased version of S, i.e. words start with title case615 characters, all remaining cased characters have lower case.616 """617 return ""618 619 def translate(self, table): # real signature unknown; restored from __doc__620 """621 S.translate(table) -> str622 623 Return a copy of the string S in which each character has been mapped624 through the given translation table. The table must implement625 lookup/indexing via __getitem__, for instance a dictionary or list,626 mapping Unicode ordinals to Unicode ordinals, strings, or None. If627 this operation raises LookupError, the character is left untouched.628 Characters mapped to None are deleted.629 """630 return ""631 632 def upper(self): # real signature unknown; restored from __doc__633 """634 """635 将字符串中的小写字母转为大写字母636 """637 S.upper() -> str638 639 Return a copy of S converted to uppercase.640 """641 return ""642 643 def zfill(self, width): # real signature unknown; restored from __doc__644 """645 """646 返回指定长度的字符串,原字符串右对齐,前面填充0647 """648 S.zfill(width) -> str649 650 Pad a numeric string S with zeros on the left, to fill a field651 of the specified width. The string S is never truncated.652 """653 return ""654 655 def __add__(self, *args, **kwargs): # real signature unknown656 """ Return self+value. """657 pass658 659 def __contains__(self, *args, **kwargs): # real signature unknown660 """ Return key in self. """661 pass662 663 def __eq__(self, *args, **kwargs): # real signature unknown664 """ Return self==value. """665 pass666 667 def __format__(self, format_spec): # real signature unknown; restored from __doc__668 """669 S.__format__(format_spec) -> str670 671 Return a formatted version of S as described by format_spec.672 """673 return ""674 675 def __getattribute__(self, *args, **kwargs): # real signature unknown676 """ Return getattr(self, name). """677 pass678 679 def __getitem__(self, *args, **kwargs): # real signature unknown680 """ Return self[key]. """681 pass682 683 def __getnewargs__(self, *args, **kwargs): # real signature unknown684 pass685 686 def __ge__(self, *args, **kwargs): # real signature unknown687 """ Return self>=value. """688 pass689 690 def __gt__(self, *args, **kwargs): # real signature unknown691 """ Return self>value. """692 pass693 694 def __hash__(self, *args, **kwargs): # real signature unknown695 """ Return hash(self). """696 pass697 698 def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__699 """700 str(object='') -> str701 str(bytes_or_buffer[, encoding[, errors]]) -> str702 703 Create a new string object from the given object. If encoding or704 errors is specified, then the object must expose a data buffer705 that will be decoded using the given encoding and error handler.706 Otherwise, returns the result of object.__str__() (if defined)707 or repr(object).708 encoding defaults to sys.getdefaultencoding().709 errors defaults to 'strict'.710 # (copied from class doc)711 """712 pass713 714 def __iter__(self, *args, **kwargs): # real signature unknown715 """ Implement iter(self). """716 pass717 718 def __len__(self, *args, **kwargs): # real signature unknown719 """ Return len(self). """720 pass721 722 def __le__(self, *args, **kwargs): # real signature unknown723 """ Return self<=value. """724 pass725 726 def __lt__(self, *args, **kwargs): # real signature unknown727 """ Return selfsize of S in memory, in bytes """761 pass762 763 def __str__(self, *args, **kwargs): # real signature unknown764 """ Return str(self). """765 pass
三、字节类型(bytes)
1 # a=bytes('hello','utf8') 2 # a=bytes('中国','utf8') 3 4 5 a=bytes('中国','utf8') 6 b=bytes('hello','gbk') 7 # 8 print(a) #b'\xe4\xb8\xad\xe5\x9b\xbd' 9 print(ord('h')) #其十进制 unicode 值为: 10410 print(ord('中'))#其十进制 unicode 值为:2001311 12 # h e l l o13 # 104 101 108 108 111 编码后结果:与ASCII表对应14 15 16 # 中 国17 # \xd6\xd0 \xb9\xfa gbk编码后的字节结果18 #\xe4 \xb8 \xad \xe5 \x9b \xbd utf8编码后的字节结果19 # 228 184 173 229 155 189 a[:]切片取20 21 22 c=a.decode('utf8')23 d=b.decode('gbk')24 #b=a.decode('gbk') :很明显报错25 26 print(c) #中国27 print(d) #hello
注意:对于 ASCII 字符串,因为无论哪种编码对应的结果都是一样的,所以可以直接使用 b'xxxx' 赋值创建 bytes 实例,但对于非 ASCII 编码的字符则不能通过这种方式创建 bytes 实例,需要指明编码方式。
1 b1=b'123'2 print(type(b1))3 # b2=b'中国' #报错4 # 所以得这样:5 b2=bytes('中国','utf8')6 print(b2)#b'\xe4\xb8\xad\xe5\x9b\xbd'
四、布尔值
一个布尔值只有True
、False
两种值,要么是True
,要么是False
,在Python中,可以直接用True
、False
表示布尔值(请注意大小写)
1 print(True)2 print(4>2)3 print(bool([3,4]))4 print(True+1)
与或非操作:
1 bool(1 and 0)2 bool(1 and 1)3 bool(1 or 0)4 bool(not 0)
布尔值经常用在条件判断中:
age=18if age>18:#bool(age>18) print('old')else: print('young')
五、列表(List)
5.1、场景:
A:把某个班所有的名字存起来,怎么办?
B:用变量存储
A:如班里有一百个人,你就得创建一百个变量啊,消耗大,效率低
C:大字符串存储
A:数据的操作(增删改查)将变得非常艰难,不是吗,我想知道张三的位置,你怎么办?
在这种需求下,编程语言有了一个重要的数据类型----列表(list)
5.2、什么是列表:列表(list)是以及其他语言中最常用到的数据结构之一。Python使用使用中括号 [ ] 来解析列表。列表是可变的(mutable)——可以改变列表的内容。
5.3、对应操作:
5.3.1、查找([])
1 names_class2=['张三','李四','王五','赵六'] 2 3 # print(names_class2[2]) 4 # print(names_class2[0:3]) 5 # print(names_class2[0:7]) 6 # print(names_class2[-1]) 7 # print(names_class2[2:3]) 8 # print(names_class2[0:3:1]) 9 # print(names_class2[3:0:-1])10 # print(names_class2[:])
5.3.2、增(append、insert)
insert 方法用于将对象插入到列表中,而append方法则用于在列表末尾追加新的对象
1 names_class2.append('alex')2 names_class2.insert(2,'alvin')3 print(names_class2)
5.3.3、改(重新赋值)
1 names_class2=['张三','李四','王五','赵六']2 3 names_class2[3]='赵七'4 names_class2[0:2]=['wusir','alvin']5 print(names_class2)
5.3.4、删(remove、del、pop)
1 names_class2.remove('alex')2 del names_class2[0]3 del names_class24 names_class2.pop()#注意,pop是有一个返回值的
5.3.5、其它操作
count方法统计某个元素在列表中出现的次数:
1 >>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to') 2 2 3 >>> x = [[1,2], 1, 1, [2, 1, [1, 2]]] 4 >>> x.count(1) 5 2 6 >>> x.count([1,2]) 7 1
extend方法可以在列表的末尾一次性追加另一个序列中的多个值
1 >>> a = [1, 2, 3] 2 >>> b = [4, 5, 6] 3 >>> a.extend(b) 4 >>> a 5 [1, 2, 3, 4, 5, 6]
extend 方法修改了被扩展的列表,而原始的连接操作(+)则不然,它会返回一个全新的列表
1 >>> a = [1, 2, 3] 2 >>> b = [4, 5, 6] 3 >>> a.extend(b) 4 >>> a 5 [1, 2, 3, 4, 5, 6] 6 >>> 7 >>> a + b 8 [1, 2, 3, 4, 5, 6, 4, 5, 6] 9 >>> a 10 [1, 2, 3, 4, 5, 6]
index 方法用于从列表中找出某个值第一个匹配项的索引位置:
1 names_class2.index('李四')
reverse方法将列表中的元素反向存放:
1 x = [4, 6, 2, 1, 7, 9]2 x.sort()#x.sort(reverse=True)
5.3.6、深浅拷贝
现在,大家先不要理会什么是深浅拷贝,听我说,对于一个列表,我想复制一份怎么办呢?
肯定会有同学说,重新赋值呗:
1 names_class1=['张三','李四','王五','赵六']2 names_class1_copy=['张三','李四','王五','赵六']
这是两块独立的内存空间
这也没问题,还是那句话,如果列表内容做够大,你真的可以要每一个元素都重新写一遍吗?当然不啦,所以列表里为我们内置了copy方法:
1 names_class1=['张三','李四','王五','赵六',[1,2,3]] 2 names_class1_copy=names_class1.copy() 3 4 names_class1[0]='zhangsan' 5 print(names_class1) 6 print(names_class1_copy) 7 8 ############ 9 names_class1[4][2]=510 print(names_class1)11 print(names_class1_copy)12 13 #问题来了,为什么names_class1_copy,从这一点我们可以断定,这两个变量并不是完全独立的,那他们的关系是什么呢?为什么有的改变,有的不改变呢?
这里就涉及到我们要讲的深浅拷贝了:
1 #不可变数据类型:数字,字符串,元组 可变类型:列表,字典 2 3 # l=[2,2,3] 4 # print(id(l)) 5 # l[0]=5 6 # print(id(l)) # 当你对可变类型进行修改时,比如这个列表对象l,它的内存地址不会变化,注意是这个列表对象l,不是它里面的元素 7 # # this is the most important 8 # 9 # s='alex'10 # print(id(s)) #像字符串,列表,数字这些不可变数据类型,,是不能修改的,比如我想要一个'Alex'的字符串,只能重新创建一个'Alex'的对象,然后让指针只想这个新对象11 #12 # s[0]='e' #报错13 # print(id(s))14 15 #重点:浅拷贝16 a=[[1,2],3,4]17 b=a[:]#b=a.copy()18 19 print(a,b)20 print(id(a),id(b))21 print('*************')22 print('a[0]:',id(a[0]),'b[0]:',id(b[0]))23 print('a[0][0]:',id(a[0][0]),'b[0][0]:',id(b[0][0]))24 print('a[0][1]:',id(a[0][1]),'b[0][1]:',id(b[0][1]))25 print('a[1]:',id(a[1]),'b[1]:',id(b[1]))26 print('a[2]:',id(a[2]),'b[2]:',id(b[2]))27 28 29 print('___________________________________________')30 b[0][0]=831 32 print(a,b)33 print(id(a),id(b))34 print('*************')35 print('a[0]:',id(a[0]),'b[0]:',id(b[0]))36 print('a[0][0]:',id(a[0][0]),'b[0][0]:',id(b[0][0]))37 print('a[0][1]:',id(a[0][1]),'b[0][1]:',id(b[0][1]))38 print('a[1]:',id(a[1]),'b[1]:',id(b[1]))39 print('a[2]:',id(a[2]),'b[2]:',id(b[2]))#outcome
# [[1, 2], 3, 4] [[1, 2], 3, 4] # 4331943624 4331943752 # ************* # a[0]: 4331611144 b[0]: 4331611144 # a[0][0]: 4297375104 b[0][0]: 4297375104 # a[0][1]: 4297375136 b[0][1]: 4297375136 # a[1]: 4297375168 b[1]: 4297375168 # a[2]: 4297375200 b[2]: 4297375200 # ___________________________________________ # [[8, 2], 3, 4] [[8, 2], 3, 4] # 4331943624 4331943752 # ************* # a[0]: 4331611144 b[0]: 4331611144 # a[0][0]: 4297375328 b[0][0]: 4297375328 # a[0][1]: 4297375136 b[0][1]: 4297375136 # a[1]: 4297375168 b[1]: 4297375168 # a[2]: 4297375200 b[2]: 4297375200 那么怎么解释这样的一个结果呢?,请看如下图所示:
列表补充:
1 b,*c=[1,2,3,4,5]