- num1 = (2, 3, 4, 5, 6)
- num2 = (1,) # 创建一个元素的元组,重要
- num3 = (1) # 不是元祖,只是数值为1的对象
- num4 = () # 空元组
- num5 = tuple(range(0, 20, 2)) # 使用
- # tuple()函数创建数值元祖,当前为偶数元组
- string1 = ('china', 'hello', 'world')
- string2 = (82, 'python', [1, 2, 3, 4])
-
- string3 = 'python', '你好', '人生苦短'
- # (注意:圆括号可以省略)
- tup1 = (12, 34.56)
- tup2 = ('abc','xyz')
- tup1[0] = 100 # 报错
- tup1 = (23, 45, 78) # 整体重新赋值
- tup3 = tup1 + tup2
- tup = ('a','b', ['A','B'])
- tup[2][0] ='X'
- tup[2][1] ='Y'
- print(tup) # 显示:('a','b', ['X','Y'])
- tup1 = (1, 2, 3)
- list1 = [4, 5, 6]
- tup2 = tup1 + list1 # 报错
- tup3 = tup1 +'china' # 报错
元组连接只有一个元素的元组时,必须加逗号
- tup1 = (1, 2, 3)
- tup2 = tup1 + (4) # 报错 改为
- tup2=tup1+(4,)
- num1 = (1, 2, 3, 4, 5)
- str1 = ('apple','orange')
- print(num1[0], str1[1])
- import random
-
- tp1 = tuple(random.sample(range(30),10))
- print(tp1)
- print(tp1[1:3])
- print(tp1[:4])
- print(tp1[5:])
- print(tp1[-2:])
- print(tp1[-3:3:-1])
- print(tp1[0:5:3])
- # 下列程序报错
- tp1 = (123,'hello','asckii')
- num = tp1.pop() # pop() 函数用于随机移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
- tp1 = (123,'hello','asckii')
- print(len(tp1)) # len()正常使用
- tp1 = (123,'hello','999', 35.6)
- list1 = list(tp1)
- list1.append('china')
- print(list1)
- tp1 = tuple(list1)
- print(tp1)