Python|自定义长度矩阵
有时,我们需要在Python中从包含元素的列表中初始化一个可变长度的矩阵。在本文中,我们将讨论可变长度方法的初始化以及这样做的某些速记。让我们讨论执行此操作的某些方法。
方法 #1:使用zip()
+ 列表理解
zip函数与列表推导相结合可以帮助实现这一特定任务。 zip函数可以帮助使用元素列表压缩计数器列表,列表推导式完成矩阵的构造工作。
# Python3 code to demonstrate
# Custom length Matrix
# using zip() + list comprehension
# initializing list
test_list = ['a', 'b', 'c']
# initializing counter list
counter_list = [1, 4, 2]
# printing original list
print ("The original list is : " + str(test_list))
# printing counter list
print ("The counter list is : " + str(counter_list))
# using zip() + list comprehension
# Custom length Matrix
res = [[i] * j for i, j in zip(test_list, counter_list)]
# printing result
print ("The custom length matrix is : " + str(res))
输出 :
The original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]
方法 #2:使用map() + mul operator
这个特殊问题也可以使用内置的 mul运算符来解决,该运算符执行喜欢的索引元素的乘法,而 map函数执行矩阵形成的任务。
# Python3 code to demonstrate
# Custom length Matrix
# using map() + mul operator
from operator import mul
# initializing list
test_list = ['a', 'b', 'c']
# initializing counter list
counter_list = [1, 4, 2]
# printing original list
print ("The original list is : " + str(test_list))
# printing counter list
print ("The counter list is : " + str(counter_list))
# using map() + mul operator
# Custom length Matrix
res = list(map(mul, [['a'], ['b'], ['c']], counter_list))
# printing result
print ("The custom length matrix is : " + str(res))
输出 :
The original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]