Python 之 tuple 元组详解

一般写法括号内最后面加个英文逗号用来区分:

一般写法括号内最后面加个英文逗号用来区分:
test = (,)
test1 = (11,22,)

例: test = (123, 456, 789, ‘abc’,)



#2.切片取值
v1, v2  =  test[1:3]    #取出456和789
print(v1, v2)

#3.可以for循环,是可迭代对象
for item in test:
    print(item)

#4.元组转化为字符串(元组内元素必须都是字符)
tu = ('abc', 'efg', 'hij',)
tu1 = "".join(tu)
print(tu1)

#5.元组转化为列表
li = list(test)
print(li)

#6.增加元素问题
# tu[2]:元组    tu[3]:列表    tu[3][0]:元组    tu[6]:bool
tu = ('nihao', 333,  (44, 55,), [(888, 999,)], 54, 45, True)
#tu[3] = "aa"          # 报错,因为tu[3]作为tu元组的一级元组,不可修改,删除
tu[3].append('33')    # tu[3]是tu元组的一级元素,只是不能对tu[3]本身进行修改、删除。但是可以对tu[3]进行list的方法 

#7.tuple的count方法:获取指定元素在元组中出现的次数 
#count(self, value)
#参数:value:待查询出现次数的元素

tu = ('nihao', 333,  (44, 55,), [(888, 999,)], 54, 333, True)
v = tu.count(333)
print("获取指定元素在元组中出现的次数:",v)

#8.tuple的index方法:获取指定元素的下标(就近原则,从左往右,找到第一个就结束)
#index(self, value, start=None, stop=None)
#参数:value:待查询下标的元素
#start:查询起始下标
#stop:查询终止下标(查询到stop前一个下标)

tu = ('nihao', 333,  (44, 55,), [(888, 999,)], 54, 333, True)
v = tu.index(333, 4, 7)
print("index方法:",v)