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