tuple

tuple
# 元组也是可以切片的
l = (1, '3', '3', 'hello', [1,2,3])
print(l[-1])  # [1,2,3]
print(l[0:-1])  # (1, '3', '3', 'hello')
print(l[0::2])  # (1, '3', [1, 2, 3])

#  元组的方法
print(l.index('3'))  # 1  默认首次出现3的索引
print('从下标索引2到下标索引3 "3"第一次出现的位置是', l.index('3', 2, 3))  # index可以从下表位置计数
print(l.count('3'))  # 出现3的次数为2次 (不可指定位置查看次数)
print(len(l))  # 长度5,而不是索引,从1开始计数

print('----------------')
# 遍历元组
for i in l:
    print(i)

# 检查项目是否存在
print('3' in l)

# 元组的拆包 必须一一对应
a ,b = (1, 2)
print('a 的值%s,b的值%s'% (a, b))
a, *b, c = (1,2,3,4)
print(a, b, c)  #  1 [2, 3] 4
*a, b, c = range(10)
print(a, b, c)  # [0, 1, 2, 3, 4, 5, 6, 7] 8 9


# 元组不可更改, 但是元组中的列表是可更改的
t = (1, [1, 2, 3])
t[1].append(6)
print(t)  # (1, [1, 2, 3, 6])
'''创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。
但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。'''
t = ("apple", "banana", "cherry")
l = list(t)
l[0] = 'hello'
print(t)  # ['apple', 'banana', 'cherry']
t = tuple(l)
print(t)  #('hello', 'banana', 'cherry')
# 元组的合并
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3, 't')

tuple3 = tuple1 + tuple2
print(tuple3)   # ('a', 'b', 'c', 1, 2, 3, 't')

# 也可以使用 tuple() 构造函数来创建元组。
thistuple1 = tuple(("apple", "banana", "cherry"))  # 请注意双括号
print(thistuple1)

# 单个元素,要加入逗号才是元组
thistuple = ("apple",)
print(type(thistuple))
# 完全删除元组
del thistuple  # 任何东西都删除了,不存在了
原文地址:https://www.cnblogs.com/jnsn/p/12731013.html