Python學習(四)數據結構 —— list tuple range


序列類型 list   tuple   range

 

  list 和 tuple

    list:   列表,由 [] 標識; 有序;可改變列表元素

    tuple:  元組,由 () 標識; 有序;不可改變元組元素(和list的主要區別)

    list 和 tuple 的創建:

 1 print([])                             # 空list
 2 print(["a",1,True])                   # 元素類型不限
 3 print([x for x in range(0,6)])        # 列表推導式
 4 print(list("a"),type(list("a")))      # 強制轉化
 5 
 6 print(())                             # 空tuple
 7 print((1))                            # 不是tuple
 8 print((1,))                           # 單一元素tuple 一定要加,
 9 print(("a",1,True))                   # 元素類型不限
10 print(tuple("a"),type(tuple("a")))    # 強制轉化

空list l = [] 

list 用一對方括號,用','隔開里面的元素  l = [a]   l = ["a",1,True]  元素類型不限

列表推導式,如:[x for x in range(0,6)] (下方會詳細介紹 range 及 列表推導式)

類型轉換 list()


空tuple  t = () 

tuple 若只有一個元素時,注意表示為  t = (1,)  一定要有逗號

tuple 用一對圓括號,用','隔開里面多個的元素  t = ("a",1,True)  元素類型不限

類型轉換 tuple()

 

  range

    range 可方便的生成一個等差的序列,有兩種表示 range(stop) 、range(start, stop[, step]) ; 通常用在 for循環語句中

    range(stop) 表示 0 到 stop(不包含stop) 等差為1 的數,如 range(4) 表示 0 1 2 3

    range(start, stop[, step]) 表示 從 start 到 stop(不包含stop) 等差為step的數;step缺省為1,可設置為負數

 1 print(type(range(4)))                   # range本身就是一個type
 2 for i in range(4):
 3     print(i)                            # 0 1 2 3
 4 for i in range(-1):                     # 從0計數,無值
 5     print(i)
 6 for i in range(4,7):                    # 4 5 6
 7     print(i)
 8 for i in range(2,7,2):                  # 2 4 6
 9     print(i)
10 for i in range(5,2,-1):                 # 5 4 3
11     print(i)

 

  序列操作

    一般操作,不改變list本身

Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n or n * s n shallow copies of s concatenated
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before index j)
s.count(x) total number of occurrences of x in s
 1 s = ["a",1,True,["b"],2]        
 2 print("a" in s)                # 判斷元素存在於s
 3 print("a" not in s)            # 判斷元素不存在於s
 4 print("b" in s)
 5 print(1.0 in s)                # 這邊不判斷int float類型不同
 6 print("1" in s)                # 這邊的1為字符串
 7 a = [1,2]
 8 b = [2,1,0]
 9 print(a+b)                     # 序列相加
10 print(a*3)                     # 序列乘法
11 s = [0,1.0,2,3,4,5,6,7,8] 
12 print(s[0],s[2],s[3])          # 通過下標來取出對應的元素
13 print(type(s[0]))            
14 print(type(s[1]))
15 print(s[2:4])                  # 取出一段list
16 print(s[2:7:2])                # 根據步長取出一段list
17 print(len(s))                  # list長度,即包含幾個元素
18 sum = 0                        
19 for i in range(0,len(s)):      # 使用for循環來取出list的每個元素
20     print(s[i])
21     sum += i                   # 賦值的簡單表達式,相當於 sum = sum + i
22 print(sum)                     # 總和
23 print(min(s),max(s))           # 取最小/最大;注意元素類型間若不可比較,會報錯
24 s = [2,3,1,2,2,3]
25 print(s.index(2))              # 查找對應元素第一次出現的下標
26 # print(s.index(4))            # 不存在該元素會報錯
27 print(s.index(2,3))            # 從下標為3的開始找起
28 print(s.index(2,3,4))          # 從下標為3到下標4的階段內找
29 print(s.count(2))              # 輸出為2的元素的個數
30 print(s.count("2"))            # 找不到匹配元素,返回0

       上方列出的操作方法對 tuple 也都適用,因為並不改變序列本身的元素,如

1 s = (2,3,1,2,2,3)
2 print(s[2],s[2:4],len(s),s.count(2))            # 對tuple均適用    

 

    改變序列的操作:僅對 list 適用;若對 tuple 操作,會報錯;clear() 和 copy() 是 Python 3.3 才新增的方法

Operation Result
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
s[i:j:k] t the elements of s[i:j:k] are replaced by those of t
del s[i:j] same as s[i:j] = []
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.pop([i]) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] == x
s.clear() removes all items from s (same as del s[:])
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.extend(t) extends s with the contents of t (same as s[len(s):len(s)] t)
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] [x])
s.copy() creates a shallow copy of s (same as s[:])
s.reverse() reverses the items of s in place

 

    list的增、刪、改的操作實際都比較實用,需要熟練掌握

    list元素更改

      可對 list 不同的下標表示法做以下操作,一般 list 下標的操作僅作對單一元素的更改賦值,如 s[0]=1 ;對多個元素的操作見下方示例(僅供參考)

 1 s = [0,1,2,3]
 2 s[0] = "1"
 3 print(s)                        # 對list的某一元素賦另外的值,類型也跟隨改變
 4 s[4] = 1                        # 不可超過原list的長度,會報錯
 5 s[0:3] = [2,3,4]                # 可對一段元素賦另外的值
 6 print(s)        
 7 s[0:3] = ["x","x"]                # 可缺少,元素個數也就相應的減少了
 8 print(s)        
 9 s[0:2] = ["x","x","x","x"]        # 可增加,元素個數也就相應的減加了
10 print(s)    
11 s[0] = [0,0]                    # 單個元素注意,相當於賦值,把序列賦予該元素
12 print(s)    
13 s[1:2] = [0,0]                
14 print(s)    
15 s = [0,1,2,3,4,5,6,7,8]
16 s[1:8:2] = ["x"]*4            
17 # s[1:8:2] = ["x"]*3            # 這種表示方式元素個數一定需要相同,不然會報錯
18 print(s)
list operation

    list元素刪除

 1 s = [0,1,2,3,4,5,6,7,8]
 2 del s[0:4]                        # 刪除對應的元素    
 3 print(s)    
 4 s = [0,1,2,3,4,5,6,7,8]
 5 del s[1:8:2]                      # 做刪除
 6 print(s)
 7 s = [0,1,2,3,4,5,6,7,8]
 8 s.pop(3)
 9 print(s.pop(3),s)                 # 做刪除,並且返回該元素的值
10 print(s.pop(),s)                  # 默認刪除最后一個
11 s = [2,"1",1.0,1,2,1]
12 s.remove(1)                       # 刪除第一個值為 1 的元素
13 print(s)                    
14 s.clear()                         # 置空,Python3.3引入
15 print(s)

 

    list元素增加

1 s = [0,1,2,3,4]
2 s.append(5)                        # list 最后加一個元素
3 print(s)
4 s.extend([6,7])                    # list 最后拼接序列
5 print(s)
6 s.extend(range(3))
7 print(s)
8 s.insert(1,["x"])                  # 在1的位置插入["x"]
9 print(s)

 

     其他操作,reverse、copy 等

 1 s = [1,2,3]
 2 c = s.copy()                    # 相當於 c = s
 3 print(c)
 4 c.reverse()
 5 print(c)
 6 s = [2,3,1,4]
 7 s.sort()                        # 排序
 8 print(s)
 9 # s = ["b",1,"a",True]          # 報錯,必須是可比較的類型
10 s = ["b","a"]
11 s.sort()    
12 print(s)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM