元组与列表类似。不同点为:
①格式不同,元组数据使用‘()’小括号,列表数据使用‘[]’方括号;
②元组中的元素不允许修改、删除等操作。即,改变元组中元素的操作都不被允许。
③元组只存在一个元素时,需要使用‘,’逗号结尾,否则结果默认为对应元素的类型而不是元组。但是列表只有一个元素时,不需要使用逗号。
t = (1)
print(type(t))
t1 = (1,)
print(type(t1))
l = [1]
print(type(l))
l1 = [1,]
print(type(l1))
运行结果:
相同点为:
①元组支持索引查找元素(索引从0开始,-1表示最后一个元素位置)
②元组支持切片操作(t[1:3:2],第一个数字表示开始的索引包含该位置,第二数字表示结束位置且不包含当前位置,第三个数字表示步长)
t = (1, 2, 4, 6, 7, 9)
print(t[1])
print(t[-1])
print(t[1:3])
print(t[::2])
print(t[::-1])
运行结果:
函数/方法 | 说明 | 举例 |
len()函数 | 获取元组长度。 | t = (1, 2, 4, 6, 7, 9) print(len(t)) ==> 6 |
max()函数 | 获取元组中最大值。 不同类型的值无法比较。相同类型值根据ASCII码值比较。 | t = (1, 2, 4, 6, 7, 9) print(max(t)) ==> 9 t = ('a', 'Y', 'y') print(max(t)) ==> y t = (1, 6, 7, 9, 'y') print(max(t)) ==> TypeError: '>' not supported between instances of 'int' and 'str' |
min()函数 | 获取元组中最小值。 不同类型的值无法比较。相同类型值根据ASCII码值比较。 | t = (1, 2, 4, 6, 7, 9) print(max(t)) ==> 1 t = ('a', 'Y', 'y') print(max(t)) ==> Y t = (1, 6, 7, 9, 'y') print(max(t)) ==> TypeError: '>' not supported between instances of 'int' and 'str' |
tuple()函数 | 转换类型为元组。 |
|