1. 程式人生 > 實用技巧 >Python資料型別——列表

Python資料型別——列表

列表

【注】 序列的定義:有序元素的集合, 可以通過下標偏移量實現隨機訪問。常見的序列有:字串、列表、元組

列表的定義

列表是Python中最具靈活性的有序集合物件型別

列表的特點

  • 用逗號','分割;使用方括號'[]'括起來
  • 下標增長方式:從左到右-0開始增1;從右向左--1開始減1
  • 訪問方式:索引&切片

列表的方法

  1. L.append(v):將v插入到L的尾部
L = ['a','b','c','d']
L.append('e')

[out]: L = ['a','b','c','d','e']
2. L.insert(i,v):將值v插入到i的索引位置

L = ['a','b','c']
L.insert(1,'a.1')

[out]:['a', 'a.1', 'b', 'c']
3. L.index(x):返回列表中第一個值為x 的元素的索引

L = ['a','b']
L.index('a')

[out]:0
4. L.remove(v):從列表L中移除第一個找到的值V

L = ['a','a','b']
L.remove('b')

[out]:['a', 'a']
5. L.pop([i]):返回指定索引的元素,若無索引,預設最後一個元素

L = ['a','b','c','d']
p = L.pop()
print("After delete the %r, the list is %r"%(p,L))

[out]:After delete the 'd', the list is ['a', 'b', 'c']
6. L.reverse():列表倒置

L = ['a','b','c']
L.reverse()

[out]:['c', 'b', 'a']
7. L.count(x)返回x在列表中出現的次數

L = ['a','c','b','a','c','e']
L.count('b')

[out]:1
8. L.sort(key = None, reverse = False):對連結串列中的元素進行適當的排序。reverse = True為降序,reverse = False為升序(預設)

L = ['a','c','b']
L.sort(reverse = False)

[out]:['a', 'b', 'c']

列表推導式

定義:提供了從序列建立列表的簡單途徑。將一些操作應用於某個推導序列的每個元素,用其獲得的結果作為生成新列表的元素,或者根據判定條件建立子序列(相當於設定一個函式y(x),x為列表的每個元素,最終形成由y組成的列表)

形式:[<expr1> for k in L if<expr2>]

Ex.

  1. 矩陣轉置
matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print([[row[i] for row in matrix] for i in range(3)])#巢狀式列表推導式

[out]:[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

  1. 隨機生成30個整數構成列表,並計算列表均值,將列表元素減去均值構成新列表
import random
total = []
for i in range(10):
    total.append(random.randint(0,100))
print(total)#輸出列表

sum = 0
for item in total:
    sum += item
av = sum//len(total)
print([x-av for x in total])

[out]:
[93, 69, 46, 21, 21, 13, 96, 92, 14, 32]
[44, 20, -3, -28, -28, -36, 47, 43, -35, -17]