【问题标题】:I have problem with using the *mul* operator to multiply varibales我在使用 *mul* 运算符乘以变量时遇到问题
【发布时间】:2021-08-13 02:20:43
【问题描述】:

我将字符串拆分并转换为 int,我想使用 mul 运算符直接相乘。但是在打印最后一个输出时它们是错误的。

from operator import mul 
# mulptiply user input
input_string = input("Enter numbers for summing :")

print("/n")
user_list = input_string.split()
print('list:', user_list)

# for loop to iterate 
for x in range(len(user_list)):
        user_list[x] = int(user_list[x]
                           
 # calc the mul of the list   
print("Multiplication of list =", mul(user_list))

【问题讨论】:

  • mul 是一个二元运算符,它只需要 2 个参数。您不能使用单个mul 来组合列表的每个元素。为什么不简单地将它们相乘在用于将它们转换为ints 的for 循环中?下次还要发布带有完整回溯的错误消息,而不是只说“有错误”。
  • 知道了。谢谢@Selcuk

标签: python-3.x list operators multiplication


【解决方案1】:

mul 函数一次接受 2 个参数并返回它们的乘积。如果您想使用 mul 计算数字列表的乘积,您可以使用 functools.reduce 将函数累积应用于每个列表项以获得聚合结果:

from functools import reduce
from operator import mul

user_list = [2, 3, 4]
print(reduce(mul, user_list)) # outputs 24

从 Python 3.8 开始,您还可以使用 math.prod 直接计算数字列表的乘积。

【讨论】:

    猜你喜欢
    • 2015-04-19
    • 2021-08-14
    • 2022-08-18
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2017-02-03
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多