python 的List資料型態

python 的List資料型態

  • List資料型態可以用來表示任何python資料型態的有序集合,亦即將任何資料型態的資料串接在一起,可以是不同資料型態的組合,List中也可以包含另一個List,當要取出其中的資料時,可以用類似陣列的方式,指定要取出位置的資料或一個範圍的資料,如:
>>> lst=[1,2,'abc',3.4,5+6j]
>>> lst
[1, 2, 'abc', 3.4, (5+6j)]

>>> lst[4]
(5+6j)

>>> lst[3:]
[3.4, (5+6j)]

>>> lst[1:3]
[2, 'abc']

>>> lst[1:3]=[5,6]
>>> lst
[1, 5, 6, 3.4, (5+6j)]

  • List可以透過( + )的符號來組合兩個不同的List,如果是要加到尾端,則可以利用append或extend兩種方法來達成,但此兩個方法是不一樣的,可參考下面例子,分辨它們的不同。
>>> x=[1,2,3]
>>> y=[4,5,6]
>>> z=[a,b,c]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

>>> z=['a','b','c']
>>> x+y
[1, 2, 3, 4, 5, 6]
>>> x
[1, 2, 3]

>>> r=x+y
>>> r
[1, 2, 3, 4, 5, 6]

>>> x.append(y)
>>> x
[1, 2, 3, 'abc', [4, 5, 6]]

>>> x.extend(y)
>>> x
[1, 2, 3, 'abc', [4, 5, 6], 4, 5, 6]


  • List的排序可以用reverse( )函數或是.sort(reverse=True)來達成

>>> x
[0, 1, 2, 3, 4, 5]

>>> x.sort(reverse=True)
>>> x
[5, 4, 3, 2, 1, 0]
>>> x
[5, 4, 3, 2, 1, 0]
>>> x.reverse()
>>> x
[0, 1, 2, 3, 4, 5]

  • List Comprehension 表列解析,我們可以利用for 迴圈來逹成。
l=[x**2 for x in range(10)]
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]