list&tuple 运算
乘以constant
>>> x = ((1,2),) >>> x*2 ((1, 2), (1, 2)) >>> x = ((1,2)) >>> x*2 (1, 2, 1, 2) >>>
从上面可以看出,tuple或者list和一个常数相乘,会复制元素得到一个新的tuple或list,需要注意的是有无逗号,这将决定是复制元素还是 "子tuple"。
tuple或list相加
>>> a = [1,2,3,4,5] >>> a + [6] [1, 2, 3, 4, 5, 6] >>> a = (1,2,3,4,5) >>> a +(6) Traceback (most recent call last): File "<pyshell#189>", line 1, in <module> a +(6) TypeError: can only concatenate tuple (not "int") to tuple >>> a + (6,) (1, 2, 3, 4, 5, 6) >>> type((6)) <type ‘int‘> >>> type([6]) <type ‘list‘> >>>
tuple和list在此处略有区别
时间: 2024-12-09 15:17:55