📜  Python – 列表上的常量乘法

📅  最后修改于: 2022-05-13 01:55:27.367000             🧑  作者: Mango

Python – 列表上的常量乘法

在使用Python列表时,我们可能会遇到需要将常量乘以列表中每个元素的情况。我们可能需要对每个元素进行迭代和乘法运算,但这会增加代码行。让我们讨论执行此任务的某些速记。

方法#1:使用列表理解
列表推导式只是执行我们使用朴素方法执行的任务的捷径。这主要用于节省时间,并且在代码的可读性方面也是最好的。

Python3
# Python3 code to demonstrate
# Constant Multiplication over List
# using list comprehension
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# using list comprehension
# Constant Multiplication over List
res = [x * K for x in test_list]
 
# printing result
print ("The list after constant multiplication : " + str(res))


Python3
# Python3 code to demonstrate
# Constant Multiplication over List
# using map() + operator.mul
import operator
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K list
K_list = [4] * len(test_list)
 
# using map() + operator.mul
# Constant Multiplication over List
res = list(map(operator.mul, test_list, K_list))
 
# printing result
print ("The list after constant multiplication : " + str(res))


输出
The original list is : [4, 5, 6, 3, 9]
The list after constant multiplication : [16, 20, 24, 12, 36]


方法 #2:使用 map() + 运算符.mul
这类似于上述函数,但使用运算符.mul 将每个元素与应用 map函数之前形成的另一个 K 列表中的另一个元素相乘。它将列表的相似索引元素相乘。

Python3

# Python3 code to demonstrate
# Constant Multiplication over List
# using map() + operator.mul
import operator
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K list
K_list = [4] * len(test_list)
 
# using map() + operator.mul
# Constant Multiplication over List
res = list(map(operator.mul, test_list, K_list))
 
# printing result
print ("The list after constant multiplication : " + str(res))
输出
The original list is : [4, 5, 6, 3, 9]
The list after constant multiplication : [16, 20, 24, 12, 36]