元组
「元组」定义语法为:(元素1, 元素2, ..., 元素n)
- 小括号把所有元素绑在一起
- 逗号将每个元素一一分开
1. 创建和访问一个元组
- Python 的元组与列表类似,不同之处在于tuple被创建后就不能对其进行修改,类似字符串。
- 元组使用小括号,列表使用方括号。
- 元组与列表类似,也用整数来对它进行索引 (indexing) 和切片 (slicing)。
例子:
t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>
print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1]) # 2
print(tuple1[5:]) # (6, 7, 8)
print(tuple1[:5]) # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2)
输出:
(1, 10.31, 'python') <class 'tuple'>
(1, 10.31, 'python') <class 'tuple'>
2
(6, 7, 8)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, 6, 7, 8)
- 创建元组可以用小括号 (),也可以什么都不用,为了可读性,建议还是用 ()。
- 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。
例子:
x = (1)
print(type(x)) # <class 'int'>
x = 2, 3, 4, 5
print(type(x)) #