標籤:元組 遍曆 方法
元組的定義。
使用( )來定義。
null_tuple = () #定義一個空元組
one_element = (‘one‘, ) #定義一個元素的元組,注意:只有一個元素後面必須帶逗號
元組的修改、增加和刪除元素。
元組是不可以修改,增加和刪除元素的!。
但,元素是dict、list型,可以更改dict、list的值。
元組元素的讀取。
exp_tuple = (‘one‘, ‘this‘, ‘is‘, ‘a‘, ‘tuple‘, 2, 3, 4, 5)
exp_tuple[起始位置:結束位置:步長]
#從左向右,第一個元素的位置是0
#從右向左,第一個元素地位置是-1
#讀取的元素個數 = 結束位置 - 起始位置
#從起始位置開始讀取
exp_tuple = (‘one‘, ‘this‘, ‘is‘, ‘a‘, ‘tuple‘, 2, 3, 4, 5)read_0 = exp_tuple[0:0]read_1 = exp_tuple[0:1]read_2 = exp_tuple[1:5]read_3 = exp_tuple[::2]read_4 = exp_tuple[-2:-1]print(read_0)print(read_1)print(read_2)print(read_3)print(read_4)
-------------------------元組的運算-------------------------
元組的運算和方法:
| + |
元組拼接,將兩個元組合在一起,產生新的元組: tuple3 = tuple1 + tuple2 |
| * |
元組複製,tuple = (0, 1); tuple * 3, 把元組複製3次,(0, 1, 0, 1, 0, 1) |
| del |
刪除元組,清除變數和記憶體值,調用報錯。tp = (0, 1); del tp |
| in |
條件判斷:元素在列表裡,返回Ture。tuple = (0, 1);print(1 in tuple)
遍曆元組:for i in tuple: print(i)
|
| not in |
元素不在列表裡,返回Ture。tuple = (0, 1);print(2 in tuple) |
| max |
返回元組裡最大值,同時有字串和數字,報錯。max(tuple) |
| min |
返回元組裡最小值,同時有字串和數字,報錯。min(tuple) |
| tuple |
把list轉換成元組。tuple([‘1‘, 2, ‘a‘]) |
|
|
|
|
本文出自 “回首已是空” 部落格,請務必保留此出處http://yishi.blog.51cto.com/1059986/1980901
python基礎:元組的使用