python基本数据类型之元祖tuple
元祖tuple
是对列表的二次加工,书写格式为括号(),里面放元素
元组的一级元素不可被修改,且不能被增加和删除
一般写元组的时候,推荐在最后加入逗号, 能加则加
创建元组
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
索引
tu = (111,"alex",(11,22),[(33,44)],True,33,44,) # 索引找值 v = tu[1] print(v)
alex
切片
tu = (111,"alex",(11,22),[(33,44)],True,33,44,) # 切片,区间内找值 v = tu[0:3] print(v)
(111, 'alex', (11, 22))
可以被for循环(可迭代对象)
tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
for item in tu:
print(item)
111
alex
(11,22)
[(33,44)]
True
44
有序的,排列的时候有顺序
- 转换(字符串,列表,元祖之间的转换)
s = "asd"
li = ["asdf",123]
tu = (123,321,"asdf")
v = tuple(s)
print(v)
v1 = tuple(li)
print(v1)
v2 = list(tu)
print(v2)
# 输出结果
('a', 's', 'd')
('asdf', 123)
[123, 321, 'asdf']
元组运算符
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。
| Python 表达式 | 结果 | 描述 |
|---|---|---|
| len((1, 2, 3)) | 3 | 计算元素个数 |
| (1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 |
| ('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 复制 |
| 3 in (1, 2, 3) | True | 元素是否存在 |
| for x in (1, 2, 3): print x, | 1 2 3 | 迭代 |
tuple的方法(魔法)
| 序号 | 方法及描述 | 实例 |
|---|---|---|
| 1 | len(tuple) 计算元组元素个数。 |
>>> tuple1 = ('Google', 'Baidu', 'Taobao')
>>> len(tuple1)
3
>>>
|
| 2 | max(tuple) 返回元组中元素最大值。 |
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
>>>
|
| 3 | min(tuple) 返回元组中元素最小值。 |
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
>>>
|
| 4 | tuple(seq) 将列表转换为元组。 |
>>> list1= ['Google', 'Taobao', 'JD', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
|

浙公网安备 33010602011771号