陣列?
你也許會好奇在Python裡有沒有像其它語言一樣叫做陣列(Array)的東西。在Python並沒有名叫"Array"的東西,但有個叫做"List"(串列)的資料結構,用起來跟在其它語言的陣列是差不多,不過它的功能比一般其它語言的陣列要來得更便利。
是有順序的!
List的定義是使用中括號,裡面不限定只能放數字或文字,你要放物件也可以。
1
| |
List是有順序的,所以如果你要取用List裡的第1項東西的話:
1
| |
操作
接下來我們來看看在List有哪些常用的操作。
又是切割!
>>> my_list[1:3]
[2, 3]
>>> my_list[:-1]
[1, 2, 3, 4, 5, 'aa']
>>> my_list[:]
[1, 2, 3, 4, 5, 'aa', 'bb']
新增元素
- append 在最後面加入元素,不用產生新物件,速度會比用
+快一點 - insert 在指定的位置插入新的元素
- extend 在最後面加入元素
+把兩個List給加在一起
你可能會好奇append跟extend有什麼不一樣,我們來看看實際操作:
>>> my_list = [1, 2, 3, 4, 5, "aa", "bb"]
>>> my_list.append(123)
>>> my_list
[1, 2, 3, 4, 5, 'aa', 'bb', 123]
>>> my_list.insert(1, "x")
>>> my_list
[1, 'x', 2, 3, 4, 5, 'aa', 'bb', 123]
>>> my_list.extend(['a', 'b', 'c'])
>>> my_list
[1, 'x', 2, 3, 4, 5, 'aa', 'bb', 123, 'a', 'b', 'c']
可以看到extend會把塞進去的元素先展開再貼到最後面,而append只是把給它的元素直接放到最後面而已。
搜尋
直接看程式碼比較容易理解:
>>> my_list = [1, 2, 3, 4, 5, "aa", "bb"]
>>> my_list.index("aa")
5
>>> "bb" in my_list
True
>>> "eddie" in my_list
False
刪除
>>> my_list = [1, 2, 3, 4, 5, "aa", "bb"]
>>> my_list.pop()
'bb'
>>> my_list
[1, 2, 3, 4, 5, 'aa']
>>> my_list.remove("aa")
>>> my_list
[1, 2, 3, 4, 5]
>>> my_list.remove("bb")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
Range
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
組合與拆解
>>> my_str_list = ["hello", "python", "good morning"]
>>> "-".join(my_str_list)
'hello-python-good morning'
>>> my_str = 'hello-python-good morning'
>>> my_str.split('-')
['hello', 'python', 'good morning']
排序、反轉
>>> my_list = [1, 2, 5, 8, 3, 0]
>>> my_list.sort()
>>> my_list
[0, 1, 2, 3, 5, 8]
>>> my_list.reverse()
>>> my_list
[8, 5, 3, 2, 1, 0]
List Comprehension
這個是Python的List的一個很棒的功能,可以讓你的程式碼變得更精簡,直接來看範例:
>>> print [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print [i for i in range(20) if i%2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
更多精彩內容,請見官網文件http://docs.python.org/tutorial/datastructures.html