标签:行修改 int error item 出现 assign object size error:
元组可以看成是一个不可更改的list
# 创建空元组 tuple1 = () print(‘tuple1的数据类型为:‘,type(tuple1)) print(‘tuple1 = ‘,tuple1) # 创建存在数据的元组 tuple2 = (1,) print(‘tuple2的数据类型为:‘,type(tuple2)) print(‘tuple2 = ‘,tuple2) tuple3 = 1, print(‘tuple3的数据类型为:‘,type(tuple3)) print(‘tuple3 = ‘,tuple3) # 创建包含多个数据的元组 tuple4 = (1,2,3,4,‘5‘) print(‘tuple4的数据类型为:‘,type(tuple4)) print(‘tuple4 = ‘,tuple4) # 通过tuple函数创建 tuple5 = tuple([1,2,[1,2]]) print(‘tuple5的数据类型为:‘,type(tuple5)) print(‘tuple5 = ‘,tuple5)
输出结果如下:
tuple1的数据类型为: <class ‘tuple‘> tuple1 = () tuple2的数据类型为: <class ‘tuple‘> tuple2 = (1,) tuple3的数据类型为: <class ‘tuple‘> tuple3 = (1,) tuple4的数据类型为: <class ‘tuple‘> tuple4 = (1, 2, 3, 4, ‘5‘) tuple5的数据类型为: <class ‘tuple‘> tuple5 = (1, 2, [1, 2])
# 查看元组中的某一数据 tuple6 = (1,2,3,4,‘5‘) print(‘tuple6[4] = ‘,tuple6[4]) # 切片操作 print(‘tuple6[1:4]的值:‘,tuple6[1:4]) # 切片后的元组为新的元组 tuple7 = tuple6[1::2] # [1::2]解析:取下标为1的及之后所有数据,步长为2 print(‘tuple6[1::2]的值:‘,tuple7) print(‘tuple6的id为:‘,id(tuple6)) print(‘tuple7的id为:‘,id(tuple7))
输出的结果如下:
tuple6[4] = 5 tuple6[1:4]的值: (2, 3, 4) tuple6[1::2]的值: (2, 4) tuple6的id为: 10136576 tuple7的id为: 11927504
# 对元组内的数据进行修改 tuple8 = (1,2,3,4,5) tuple8[1] = 100
输出结果如下:修改tuple内容会导致报错
TypeError: ‘tuple‘ object does not support item assignment
tuple8 = (1,2,3,4,5,1,‘2‘,3,1,2) print(‘tuple8 =‘,tuple8) # count()方法,获取到指定元素在该元组中出现的次数 n = tuple8.count(2) print(‘tuple8中整数2出现的次数有:‘,n,‘次‘) # index()方法,获取到指定元素在该元组的索引位置 # 如果需要查找的指定元素存在多个,则返回第一个的索引值 idx = tuple8.index(2) print(‘tuple8中整数2的索引位置为:‘,idx)
输出的结果如下:
tuple8 = (1, 2, 3, 4, 5, 1, ‘2‘, 3, 1, 2) tuple8中整数2出现的次数有: 2 次 tuple8中整数2的索引位置为: 1
标签:行修改 int error item 出现 assign object size error:
原文地址:https://www.cnblogs.com/wilson-5133/p/10351799.html