注意:元祖定义后不可修改,单个元祖后面必须加逗号,否则认为是字符串:tuple = ('apple',)
1.定义元祖
tuple = ('apple','banana','grape','orange') print(tuple[-1]) #orange print(tuple[-2]) #grape tuple2 = tuple[1:3] #切片,从第二个元素到第三个元素(不包括第四个元素) tuple3 = tuple[0:-2] #切片,从第一个元素开始到倒数第二个元素(不包括倒数第二个)
2.元祖的打包与解包
#打包 tuple = ('apple','banana','grape','orange') #解包 a,b,c,d = tuple print(a,b,c,d) #apple banana grape orange
3.建立二层元祖
tuple = (('apple','banana'),('grape','orange'),('watermelon',),('grapefruit',)) for i in tuple: print('一层-{}'.format(i)) for j in i: print('二层-{}'.format(j))