Python 中的自定義長度矩陣
有時在使用 Python 建立矩陣時,我們可能需要控制給定元素在所得矩陣中重複的次數。在本文中,我們將介紹如何使用列表作為元素來建立具有所需數量元素的矩陣。
使用 zip
我們宣告一個列表,其中包含用於矩陣的元素。然後,我們宣告一個列表,該列表將儲存元素在矩陣中的出現次數。使用 zip 函式我們可以建立結果矩陣,其中將包含用於組織元素的 for 迴圈。
示例
listA = ['m', 'n', 'p','q']
# Count of elements
elem_count = [1,0,3,2]
# Given Lists
print("Given List of elements: " ,listA)
print("Count of elements : ",elem_count)
# Creating Matrix
res = [[x] * y for x, y in zip(listA, elem_count)]
# Result
print("The new matrix is : " ,res)輸出
執行以上程式碼將產生以下結果 −
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements : [1, 0, 3, 2] The new matrix is : [['m'], [], ['p', 'p', 'p'], ['q', 'q']]
使用 map 和 mul
在此方法中,我們使用 operator 模組中的 mul 方法來代替上面的 zip 方法。此外,map 函式對列表中的每個元素應用 mul 方法,因此不需要 for 迴圈。
示例
from operator import mul
listA = ['m', 'n', 'p','q']
# Count of elements
elem_count = [1,0,3,2]
# Given Lists
print("Given List of elements: " ,listA)
print("Count of elements : ",elem_count)
# Creating Matrix
res = list(map(mul, listA, elem_count))
# Result
print("The new matrix is : " ,res)輸出
執行以上程式碼將產生以下結果 −
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements : [1, 0, 3, 2] The new matrix is : ['m', '', 'ppp', 'qq']
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP