Python基础----元组

Python的元组与列表类似,不同之处:

a、元组的元素不能修改,列表可以,只读型的列表。稳定性更高,相比较而言灵活性更低。

b、元组使用小括号,列表使用方括号

元组中只包含一个元素时,需要在元素后面添加逗号

# 元组里面只有一个元素时加逗号的必要性
a = (1)
print (type(a))   #  不加逗号为整型
a = (1,)
print (type(a))   #  加逗号才为元组
a = 2,3           #  没有括号,只要有逗号也为元组
print (type(a))
<class 'int'>
<class 'tuple'>
<class 'tuple'>

元组与字符串类似,下标索引从0开始,可以进行截取,组合等。

可以将两个元组进行组合拼接,但是不能对元组中的元素进行修改,可以对元组中的列表进行更改

a = (2,3,5,7,[1,3,5])
a[1] = 2
print (a)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-7-95366ad736b9> in <module>()
      1 a = (2,3,5,7,[1,3,5])
----> 2 a[1] = 2
      3 print (a)


TypeError: 'tuple' object does not support item assignment
a = (2,3,5,7,[1,3,5])
a[4][1] = 2
print (a)
(2, 3, 5, 7, [1, 2, 5])

tuple取反操作

a = (2,3,5,7,[1,3,5])
print(a[::-1])
b = 'tuple same as str'
print (b[::-1])
c = [2,4,6,8]
print (c[::-1])
([1, 3, 5], 7, 5, 3, 2)
rts sa emas elput
[8, 6, 4, 2]
dir(tuple)
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']

元组的常用方法count/index,与list类似

t = (2, 1, 1, 2) 
print (t.count(1))
print (t.index(1))
2
1

Python元组常用内置函数

cmp(tuple1,tuple2):比较两个tuple

len(tuple1),获取tuple1的长度

max(tuple1),获取tuple1中元素最大值

min(tuple1),获取tuple1中元素最小值

tuple(seq),将列表转化为tuple

del tuple , 删除元组

猜你喜欢

转载自blog.csdn.net/weixin_42432468/article/details/88565076
今日推荐