1. 程式人生 > >字串、列表、元組(string, list, tuple)的區別

字串、列表、元組(string, list, tuple)的區別

字串、列表、元組這三個統稱為序列(sequence),三者有很多共性,也有自己的特性,本文先介紹如何新建,如何訪問,以及如何更新來介紹列表,最後來介紹三者的共有函式和特有的內建函式。

一、如何新建序列並賦值

 1astring = "Hello world"#使用雙引號字串,三引號用於新建多行字串
 2astring1 = 'hello world'#使用單引號字串
 3atring2 = """
 4          Today is sunday,
 5          and very hot 
 6         """
 7s = [123, 'abc', 456, 7-9j]
 8list("foo")#使用工廠方法來新建,其輸出為['f', 'o', 'o']
 9t = (['xyz', 123], 456, 123.4)#元組用圓括號並表示,列表用方括號表示
10t*2#其輸出為(['xyz', 123], 456, 123.4, ['xyz', 123], 456, 123.4)

再補充一下里面沒有的: enumerate() 函式用於將一個可遍歷的資料物件(如列表、元組或字串)組合為一個索引序列,同時列出資料和資料下標,一般用在 for 迴圈當中 語法為enumerate(sequence, [start=0])

1f =  ['tables', 'avdfd', 'robot', 'pyramid']
2for i, j  in enumerate(f):
3    print (i,j)
4
5
6seasons = ['Spring', 'Summer', 'Fall', 'Winter']
7list(enumerate(seasons, start=1))       # 小標從 1 開始

其輸出為

1          0 tables
2          1 avdfd
3          2 robot
4          3 pyramid
5
6
7[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

zip() 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的物件,這樣做的好處是節約了不少的記憶體

1a = [1,2,3]
2b = [4,5,6]
3c = [7, 8, 9, 10]
4zipped = zip(a,b)     # 返回一個物件
5list(zipped)  # list() 轉換為列表
6
7t = (zip(a,c))  # 元素個數與最短的列表一致
8t
9list(t)
1[(1, 4), (2, 5), (3, 6)]
2
3<zip at 0x25a57d7bbc8>
4
5[(1, 7), (2, 8), (3, 9)]

二、如何訪問列表

三者都可以進行切片操作,順序訪問時從零開始,0,1,2,3,倒序訪問從-1開始 -4,-3,-2, -1 sequence[starting_index, ending_index, step] [:]表示整個序列 [: : -1]表示反序操作 [0:3]/[:3]表示str[0]到[2]含頭不含尾 [3:]表示從str[3]到最後

1astring = "Hello world"
2astring[:7] 其輸出為'Hello w' 注意空格算一個字元
3t = (['xyz', 123], 456, 123.4)
4t[0][1]#其輸出為123,元組的第零個元素是列表,然後再求列表的第一個元素
5s = [123, 'abc', 456, 7-9j]
6s[::-1]#其輸出為[(7-9j), 456, 'abc', 123]
7s[:]#其輸出為[123, 'abc', 456, (7-9j)]

三、可變型別和不可變型別

字串和元組是不可變型別,列表是可變型別 比如“abcd”字串要想改變成bacd必須新建一個物件 而不能再本地直接改,但是列表就可以 因此,排序,替換,新增對字串和元組來說就是不可能實現的

四、元組和列表很類似,但元組存在的意義是甚麼?

當我們把資料傳給一個不瞭解的API(英文解釋為Application Program Interfaces, or APIs, are commonly used to retrieve data from remote websites. Sites like Reddit, Twitter, and Facebook all offer certain data through their APIs. To use an API, you make a request to a remote web server, and retrieve the data you need.)時,可以確保我們的資料不會被修改,當需要需要改時轉換成List即可

1t = (['xyz', 123], 456, 123.4)
2t[0][1] = "789"
3t

輸出為

1(['xyz', '789'], 456, 123.4)

在這裡元組的第0個元素是列表,而列表是可變的,因此可以進行替換。 總之,元組物件本身是不可變的,但不意味著元組包含的可變物件是不可變的