DAY 011--Tuple使用方法汇总

元组使用方法汇总                                               

Python的元组和列表类似,不同之处在于元组中的元素不能修改(因此元组又称为只读列表),所以元组没有增、删、改的操作,且元组使用小括号而列表使用中括号,如下:

1、元组中只包含一个元素时                                                    

  • 需要在元素后面添加逗号来消除歧义  
tup1=("hello")
print("tup1:",type(tup1))
#输出结果
tup1: <class 'str'>

tup2=("hello",)
print("tup2:",type(tup2))
#输出结果
tup2: <class 'tuple'>


tup3=(1)
print("tup3:",type(tup3))
#输出结果
tup3: <class 'int'>

tup4=(1,)
print("tup4:",type(tup4))
#输出结果
tup4: <class 'tuple'>

2、元组中的元素值不允许修改                                        

  • 修改元组值报错
tup2=("hello","world")
tup2[0]="Hello"

#输出结果
TypeError: 'tuple' object does not support item assignment

但是可以对元组进行连接组合

  • 连接元组值
tup1=("hi",)
tup2=("hello","world")
print(tup1+tup2)

#输出结果
('hi', 'hello', 'world')

3、元组中的元素是不允许删除的                                             

但是可以使用del语句来删除整个元组

  • del tuple
tup2=("hello","world")
del tup2

4、元组之间可以使用+和*                                                     

即允许元组进行组合连接和重复复制,运算后会生成一个新的元组

  • tuple1+tuple2
  • M*tuple*N
tup1=("hi",)
tup2=("hello","world")

print(tup1+tup2)
#输出结果
('hi', 'hello', 'world')

print(2*tup1*2)
#输出结果
('hi', 'hi', 'hi', 'hi')

5、元组运行切片操作                                                              

  • tuple[index:index:step]
tup=(1,2,3,4,5,6,7,8,9)
print(tup[::2])

#输出结果
(1, 3, 5, 7, 9)

6、任意无符号的对象,以逗号隔开,默认为元组                           

str1="你好","明天"
print(type(str1))

#输出结果
<class 'tuple'>

7、对元组进行操作的内建函数                                                  

  • cmp(tup1,tup2):   比较两个元组元素,只针对python2而言,对于python3,需要用到operator模块。
  • operator模块(从第一个数字或字母(ASCII)比大小 ,返回值为布尔)
    • lt(a,b)  相当于  a<b
    • le(a,b) 相当于 a<=b
    • eq(a,b) 相当于 a==b
    • ne(a,b) 相当于 a!=b
    • gt(a,b) 相当于 a>b
    • ge(a,b) 相当于 a>=b
import operator
tup1=(1,2)
tup2=(1,2,3)
print(operator.le(tup1,tup2))

#输出结果
True
  • len(tup):     返回元组中元素的个数
tup2=(1,2,3)
print(len(tup2))

3
  • max(tup):   返回元组中元素最大的值
tup2=(1,2,3)
print(max(tup2))

3
  • min(tup):    返回元组中元素最小的值
tup2=(1,2,3)
print(min(tup2))

1
  • tuple(seq):  将列表转化为元组
l=[1,2,3,4]
print(tuple(l),type(tuple(l)))

(1, 2, 3, 4) <class 'tuple'>

8、元组的方法(查)                                                              

  • tuple.index(obj):从元组中找出某个值第一个匹配项的索引值
tup2=(1,2,3)
print(tup2.index(3))

#输出结果
2
  • tuple.count(obj): 统计某个元素在元组中出现的次数
tup2=(1,2,3,4,1)
print(tup2.count(1))

#输出结果
2

Mark on 2018.04.10

原文地址:https://www.cnblogs.com/JunSheep/p/8778122.html