Python 列表乘法程序

编写一个 Python 程序,使用 for 循环范围执行列表乘法。在此示例中,我们允许用户输入列表项。接下来,我们使用 for 循环范围 (for i in range(listNumber)) 来迭代 multiList 列表项。在循环内,我们对每个列表项进行乘法运算并打印结果。

multiList = []

listNumber = int(input("Enter the Total List Items = "))
for i in range(1, listNumber + 1):
    listValue = int(input("Enter the %d list Item = " %i))
    multiList.append(listValue)

print("List Items = ", multiList)

listMultiplication = 1

for i in range(listNumber):
    listMultiplication = listMultiplication * multiList[i]
    

print("The Muliplication of all teh List Items = ", listMultiplication)
List Multiplication Program

使用 For 循环的 Python 列表乘法程序

multiList = []

listNumber = int(input("Enter the Total List Items = "))
for i in range(1, listNumber + 1):
    listValue = int(input("Enter the %d List Item = " %i))
    multiList.append(listValue)

print("List Items = ", multiList)

listMulti = 1

for num in multiList:
    listMulti = listMulti * num

print(listMulti)
Enter the Total List Items = 5
Enter the 1 List Item = 10
Enter the 2 List Item = 4
Enter the 3 List Item = 9
Enter the 4 List Item = 11
Enter the 5 List Item = 7
List Items =  [10, 4, 9, 11, 7]
27720

此程序使用 While 循环执行列表乘法。

multiList = []

listNumber = int(input("Enter the Total Items = "))
for i in range(1, listNumber + 1):
    listValue = int(input("Enter the %d Item = " %i))
    multiList.append(listValue)

print("List Items = ", multiList)

listMultiplication = 1
i = 0

while (i < listNumber):
    listMultiplication = listMultiplication * multiList[i]
    i = i + 1
    
print("Result = ", listMultiplication)
Enter the Total Items = 4
Enter the 1 Item = 9
Enter the 2 Item = 10
Enter the 3 Item = 2
Enter the 4 Item = 4
List Items =  [9, 10, 2, 4]
The Result =  720

在此列表 示例 中,我们创建了一个 listMultiplication(multiList) 函数,该函数返回列表乘法的结果。在此列表 示例 中,我们创建了一个 listMultiplication(multiList) 函数,该函数返回列表乘法的结果。

def listMultiplication(multiList):
    listMulti = 1

    for num in multiList:
        listMulti = listMulti * num
    return listMulti

multiList = [10, 20, 8]

listMultip = listMultiplication(multiList)

print("The Result = ", listMultip)
The Result =  1600

使用内置函数的列表乘法程序

使用 math 库

math 库具有内置的 prod() 函数,该函数有助于将列表中的所有元素相乘并返回输出。

import math

a = [2, 3, 4, 5, 6]

mul = math.prod(a)

print(mul)
720

使用 numpy 模块

流行的 numpy 模块具有 prod() 函数,该函数也将执行列表乘法,此程序使用了该函数。

import numpy as np

a = [2, 3, 4, 5, 6]

mul = np.prod(a)
print(mul)
720

使用 reduce() 和 operator

默认情况下,operator 模块中的 mul() 函数接受参数,将这些值相乘并返回输出。如果将其与 reduce 函数结合使用,乘法过程将应用于所有列表项。

from functools import reduce
import operator

a = [2, 3, 2, 4, 5, 6]

mul = reduce(operator.mul, a)
print(mul)
1440