Python 元組

1 什麼是元組

Python中元組與列表相似,只是元組的元素不能更改ide

元組的建立很簡單,使用圓括號()將元素括起來便可,雖然不用括號也能夠,但不建議這麼作函數

特別的是元組只有一個元素時,須要在元素後面加一個逗號,否則括號會被當成運算符,示例以下:對象

tuple1 = ()  # 建立空元組
tuple2 = ('a')  # 單個元素後不加逗號沒法建立
tuple3 = ('a',)  # 單個元素後要加逗號
tuple4 = ('a', 'b')  # 多個元素逗號隔開
tuple5 = 'a', 'b'  # 不適用()也能夠建立元組,但不建議使用
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple5)

結果以下:blog

2 元素的操做

元組除了元素不能修改以外,其他的操做同列表,示例以下:it

tuple1 = ('張無忌', '成昆', '楊逍')
tuple2 = ('趙敏', '滅絕大師')
tuple3 = tuple1 + tuple2  # 元組拼接
tuple4 = tuple1 * 3  # 複製元素
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple1[1])  # 訪問元組元素
print(tuple1[0:2])  # 元組切片

結果以下:class

除了上面的操做外,元組也有相似列表的內置函數和方法:遍歷

  • len(tuple):計算元組元素個數方法

  • max(tuple):返回元組元素最大值im

  • min(tuple):返回元組元素最小值d3

  • tuple(iterable):將可迭代對象轉爲元組

  • item in tuple:判斷元素item是否存在

  • for item in tuple:遍歷元組元素

相關文章
相關標籤/搜索