Python中數組的幾種使用方法

二維數組的初始化

matirx_done = [[0 for i in range(0, len(matirx))]for j in range(0, len(matirx[0]))]

就將其初始化為一個與matrix相同大小的元素全為 0 的矩陣

數組的多級排序

在數組 idea_collect = [[3, 1, 2], [3, 2, 1], [3, 2, 2], [3, 1, 1]] 中, 先按照第二項排列, 再按照第三項倒序排列 可寫為:

idea_collect.sort(key=lambda x: (x[1], -x[2]))

其中, x[1] 代表第二項正序排列, -x[2] 代表第三項倒序排列

排列結果為 [[3, 1, 2], [3, 1, 1], [3, 2, 2], [3, 2, 1]]

在一個 class 中多個函數不傳參使用同一個數組

如例所示:

class Partition:      def __init__(self):          self.num_complete = []        def partition(self, num, start, end):          self.num_compelete = num        def partition_core(self):          del self.num_compelete[0] 

其中,self.num_compelete就是 class 中兩個函數同時可以直接調用的數組, 不過最好先在def __init__中聲明這個數組