1.将元组赋值给一个变量
输入:
x = tuple([3, 2, 1])
x
x[2]
输出:
(3, 2, 1)
1
2.将元组同时赋值给多个变量
输入:
X1, Y1, Z1 = tuple([3, 2, 1])
x2, y2, z2 = tuple([4, 5, 6])
X1*x2
Y1
输出:
12
2
3.将多个值同时赋值给多个变量
输入:
X1, Y1, Z1 = 3, 2, 1
X2, Y2, Z2 = 4, 5, 6
X1*X2
输出:
12
- 元组的数据不能修改,但是我们可以连接两个元组得到一个新的元组。
输入:
tuple([3, 2]) + ('0',)
输出:
(3, 2, '0')
输入:
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
tup3 = tup1 + tup2
print (tup3)
输出:
(12, 34.56, 'abc', 'xyz')
5.单个元组追加后要跟上一个逗号
例如,输入:
tuple([3, 2]) + ('0')
输出:
TypeError Traceback (most recent call last)
<ipython-input-10-175be6d1e4c5> in <module>()
----> 1 tuple([3, 2]) + ('0')
TypeError: can only concatenate tuple (not "str") to tuple
输入:
>>> a=(1,2)
>>> b=(3)
>>> print(a + b)
输出:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
输入:
>>> a=(1,2)
>>> b=(3,)
>>> print(a + b)
输出:
(1,2,3)
因为Python会把(3)当成int型,把('0')当成字符串型。
网友评论