Python List 列表的處理

Jason990420發表於2020-04-13

建立日期: 2020/04/13

更新日期: 2020/04/16

說明:本文請隨意引用或更改,只須標示出處及作者,作者不保證內容絶對正確無誤,如造成任何後果,請自行負責.

Python List 列表的處理

本文主要在於一些非常態的列表處理, 至於Python list 自帶的一些函式或方法, 請見下方Python 列表常用方法.

相關的方法會持續續加進來, 也希望讀者有一些方式不知道怎麼用的,或者有其他的方法, 敬請提示.

  1. 對列表各元素, 逐一處理
>>> import math
>>> a = [math.sqrt(i) for i in range(10)]
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]
>>> b = [list(range(1,5)), list(range(5,9)), list(range(9,13))]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
  • 建立列表直接處理
>>> # 一維方式
>>> [int(i*10)/10 for i in a]
[0.0, 1.0, 1.4, 1.7, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0]
>>> # 二維方式
>>> [[b[j][i]**2 for i in range(len(b[j]))] for j in range(len(b))]
[[1, 4, 9, 16], [25, 36, 49, 64], [81, 100, 121, 144]]
  • 使用函式, 可以重複使用, 也適合處理更復雜的狀況
>>> def def func(sequence):
...     return [int(i*10)/10 for i in sequence]
>>> print(func(a))
[0.0, 1.0, 1.4, 1.7, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0]
  • 使用 map + 函式, 可以簡化函式的處理, 更可適用在單一變數或列表
>>> def func(i):
...     return int(i*10)/10
>>> list(map(func, a))
[0.0, 1.0, 1.4, 1.7, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0]
>>> func(1.41459)
1.4
  • 使用map + lambda 方法, 可使map對應多引數的函式
>>> list(map(lambda i:int(i*10)/10, a))
[0.0, 1.0, 1.4, 1.7, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0]
  • 使用 map+lambda+function
>>> def Map(func, sequence, *argc):
...     return list(map(lambda i:func(i, *argc), sequence))
>>> Map(round, a, 2)
[0.0, 1.0, 1.41, 1.73, 2.0, 2.24, 2.45, 2.65, 2.83, 3.0]
>>> Map(int, a)
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3]
  1. 條件選擇/刪除元素
  • 使用 if 條件, 建立新列表
>>> # 一維方式
>>> [i for i in a if 2<i<3]
[2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903]
  • 使用 filter + function
>>> def func(i):
...     return 2<i<3
>>> list(filter(func, a))
[2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903]
  • 使用 filter + lambda
>>> list(filter(lambda i: 2<i<3, a))
[2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903]
  • 使用 filter + lambda + function
>>> def Filter(func, sequence, *argc):
...     return list(filter(lambda i:func(i, *argc), sequence))
>>> Filter(float.__gt__, a, 2) # 大於2>>> b = ['This', 'There', 'Where', 'Here']
>>> Filter(str.__contains__, b, 'T') # 字串中有'T'['This', 'There']
>>> Filter(str.__contains__, b, 'r') # 字串中有'r'['There', 'Where', 'Here']
  1. 展平列表
def Flat_List(sequence):
    result = []
    if isinstance(sequence, list):
        for item in sequence:
            if isinstance(item, list):
                result += Flat_List(item)
            else:
                result.append(item)
        return result
    else:
        return sequence
Flat_List([[1,2,[3,4,5],6,[7,8,[9,10],[11,12]]]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  1. 列表轉換
  • 列表與字典
>>> a = [[1,2],[3,4]]
>>> b = dict(a)
>>> b
{1: 2, 3: 4}
>>> list(map(list, b.items()))
[[1, 2], [3, 4]]
  1. 列表的排列組合
>>> a = [1,2,3]
>>> [[i, j] for i in a for j in a]
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
>>> [[i, j] for i in a for j in a if i!=j]
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
>>> from itertools import permutations, combinations, product
>>> list(map(list, permutations(a, 2)))
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
>>> list(map(list, combinations(a, 2)))
[[1, 2], [1, 3], [2, 3]]
>>> b = [4, 5, 6]
>>> list(map(list, product(a, b)))
[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
>>> list(map(list, product(a, repeat=2)))
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
  1. 列表轉置
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> list(map(list, zip(*a)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]


Python 列表常用方法

  1. 建立列表
  • 直接建立
>>> [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
  • 函式/方法/產生器建立
>>> [i for i in range(5)]
[0, 1, 2, 3, 4]
  • 一維雙變數互動建立
>>> [(i, j*10) for i in range(5) for j in range(5)]
[(0, 0), (0, 10), (0, 20), (0, 30), (0, 40), (1, 0), (1, 10), (1, 20), ( 1, 30), (1, 40), (2, 0), (2, 10), (2, 20), (2, 30), (2, 40), (3, 0), (3, 10), (3, 20), (3, 30), (3, 40), (4, 0), (4, 10), (4, 20), (4, 30), (4, 40) ]
  • 一維雙變數對應建立
>>> [(i, j*10) for i, j in zip(range(5), range(5))]
[(0, 0), (1, 10), (2, 20), (3, 30), (4, 40)]
  • 多維列表建立
>>> [[[i, j] for i in range(5)] for j in range(5)]
[[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]],
 [[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]],
 [[0, 2], [1, 2], [2, 2], [3, 2], [4, 2]],
 [[0, 3], [1, 3], [2, 3], [3, 3], [4, 3]],
 [[0, 4], [1, 4], [2, 4], [3, 4], [4, 4]]]
  • 從其他變數建立
>>> list('We are the world')
['W', 'e', ' ', 'a', 'r', 'e', ' ', 't', 'h', 'e', ' ', 'w', 'o', 'r', 'l', 'd']
>>> list(range(5))
[0, 1, 2, 3, 4]
  1. 修改列表
  • 單一元素修改
>>> a = [1, 2, 3, 5]
>>> a[3] = 4
>>> a
[1, 2, 3, 4]
  • 部份修改
>>> a[1:3] = [5, 6]
[1, 5, 6, 4]
>>> a[1:3] = [8]
[1, 8, 4]
  1. 複製列表
  • 記憶體參考位置複製
>>> a = [1, 2, 3, 4]
>>> b = a
>>> b[1] = 10
>>> a, b
([1, 10, 3, 4], [1, 10, 3, 4])
  • 一維淺層複製
>>> from copy import copy, deepcopy
>>> a = [[1,2,3], [4, 5,6]]
>>> b = copy(a) # 同 b = a[:]
>>> b[0] = [7, 8, 9] # 第一層修改不會改變被複制物件
>>> a, b
([[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [4, 5, 6]])
>>> b[0][0] = 100 # 第二層修改會改變被複制物件
>>> a, b
([[1, 2, 3], [100, 5, 6]], [[7, 8, 9], [100, 5, 6]]
  • 多維深層複製, 完全不會改變被複制物件
>>> a = [[1,2,3], [4, 5,6]]
>>> b = deepcopy(a)
>>> b[0] = [7, 8, 9]
>>> b[1][0] = 100
>>> a, b
([[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [100, 5, 6]])
  1. 增加列表內容
  • 插入
>>> a = [1, 2, 3, 4]
>>> a.insert(0, 0)
[0, 1, 2, 3, 4]
>>> a.insert(2, 12)
[0, 1, 12, 2, 3, 4]
>>> a.insert(100, 99)
[0, 1 ,12, 2, 3, 4, 99]
  • 插入多列
>>> a[2:2] = [20, 21, 22]
[0, 1, 20, 21, 22, 12, 2, 3, 4, 99]
  • 後面附上
>>> a = [0]
>>> a = a.append(1)
>>> a = a.append(2)
[0, 1, 2]
  • 重複內容
>>> a = [1,2] * 5
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
  • 列表組合
>>> a, b = [1, 2], [3, 4]
>>> a + b
[1, 2, 3, 4]
>>> c = a.extend(b)
>>> a, c
([1, 2, 3, 4], None)
  1. 刪除列表內容
  • 以索引來刪除
>>> a = [1, 2, 3, 4, 3]
>>> b = a.pop(0)
>>> a, b
([2, 3, 4, 3], 1)
  • 以值來刪除第一個
>>> a.remove(3)
[2, 4, 3]
  • 直接刪除
>>> del a[1:]
[2]
  1. 列表的其他方法
  • 計數該值出現的次數
>>> a = [1, 3, 3, 5, 3, 2, 6, 3]
>>> a.count(3)
4
  • 返回該值的第一個索引
>>> a.index(5)
3
  • 列表排序, 不修改
>>> c = sorted(a)
>>> a, c
([1, 3, 3, 5, 3, 2, 6, 3], [1, 2, 3, 3, 3, 3, 5, 6])
  • 列表排序, 自修改
>>> c = a.sort()
>>> a, c
([1, 2, 3, 3, 3, 3, 5, 6], None)
  • 倒序
>>> a = [1, 2, 3, 4]
>>> a[::-1]
[4, 3, 2, 1]
>>> c = a.reverse()
>>> a, c
([4, 3, 2, 1], None)
本作品採用《CC 協議》,轉載必須註明作者和本文連結
Jason Yang

相關文章