元组
tuple 元组
元组中的元素不能修改。
元组用 () 定义,元素之间用 , 分隔。
程序示例:
tuple1 = (1, 2.5, "hello")
print(tuple1) # (1, 2.5, 'hello')
print(type(tuple1)) # <class 'tuple'>
只有一个元素时,元素后面要加一个逗号。
程序示例:
tuple1 = ('apple')
print(tuple1) # apple
print(type(tuple1)) # <class 'str'>
tuple2 = ('apple',)
print(tuple2) # ('apple',)
print(type(tuple2)) # <class 'tuple'>
程序示例:
# 空元组
tuple1 = ()
print(tuple1) # ()
print(type(tuple1)) # <class 'tuple'>
tuple2 = tuple()
print(tuple2) # ()
print(type(tuple2)) # <class 'tuple'>
程序示例:
# 类型转换 tuple()
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
tuple1 = tuple(list1)
print(tuple1) # (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(type(tuple1)) # <class 'tuple'>
tuple2 = tuple("hello")
print(tuple2) # ('h', 'e', 'l', 'l', 'o')
print(type(tuple2)) # <class 'tuple'>
tuple3 = tuple(range(1, 5))
print(tuple3) # (1, 2, 3, 4)
print(type(tuple3)) # <class 'tuple'>
程序示例:
tuple1 = ('h', 'e', 'l', 'l', 'o')
list1 = list(tuple1)
print(list1) # ['h', 'e', 'l', 'l', 'o']
print(type(list1)) # <class 'list'>
str1 = str(tuple1)
print(str1) # ('h', 'e', 'l', 'l', 'o')
print(type(str1)) # <class 'str'>
print(str1[2]) # h,元组整体转为字符串,( 是索引为 0,' 是索引为 1,h 是索引为 2
程序示例:
# 索引
tuple1 = ('h', 'e', 'l', 'l', 'o')
print(tuple1[1]) # e
print(tuple1[-1]) # o
程序示例:
# 切片
tuple1 = (1, 2, 3, 4)
print(tuple1[::-1]) # (4, 3, 2, 1)
程序示例:
tuple1 = (1, 2, 3, 4)
print(len(tuple1)) # 4
print(max(tuple1)) # 4
print(min(tuple1)) # 1
程序示例:
tuple1 = (1, 2, 3, 4)
print(tuple1) # (1, 2, 3, 4)
del tuple1
# print(tuple1) # NameError: name 'tuple1' is not defined. Did you mean: 'tuple'?
程序示例:
tuple1 = (1, 2, 3, 4)
tuple2 = ("a", "b", "c", "d")
tuple3 = tuple1 + tuple2
print(tuple3) # (1, 2, 3, 4, 'a', 'b', 'c', 'd')
tuple4 = tuple1 * 3
print(tuple4) # (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
print("e" in tuple4) # False
print("e" not in tuple1) # True
程序示例:
tuple1 = (1, 2, 3, 4)
# tuple1[2] = 4 # TypeError: 'tuple' object does not support item assignment
程序示例:
tuple1 = (1, 2, 3, 4, 1, 2, 1)
print(tuple1.count(1)) # 3
print(tuple1.count(10)) # 0
tuple2 = ("hello", "world", "good", "morning")
print(tuple2.index("good")) # 2
# print(tuple2.index("well")) # ValueError: tuple.index(x): x not in tuple
程序示例:
# 遍历元组
tuple1 = ("hello", "world", "good", "morning")
for i in tuple1:
print(i)
结果:
hello
world
good
morning
程序示例:
# 遍历元组
tuple1 = ("hello", "world", "good", "morning")
for index, value in enumerate(tuple1):
print(index, value)
结果:
0 hello
1 world
2 good
3 morning
程序示例:
# 遍历元组
tuple1 = ("hello", "world", "good", "morning")
for i in range(len(tuple1)):
print(i, tuple1[i])
结果:
0 hello
1 world
2 good
3 morning
元组定义时的 () 并不是必须的。
程序示例:
t1 = 1,
print(t1)
print(type(t1))
结果:
(1,)
<class 'tuple'>
浙公网安备 33010602011771号