如何将我的列表乘以每个数字(迷你计算器)

时间:2014-02-18 14:25:36

标签: python list tuples calculator

我搜索了谷歌和python文档以及Stackoverflow,我真的很困惑,没有任何方法可以证明是正确的。

divisors = []


prime_numbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]        
first_fraction_number = int(input("Type the first number of your fraction " + prompt))
second_fraction_number = int(input("Type the second number of your fraction " + prompt))

        for i in range(len(prime_numbers)):

            if first_fraction_number%prime_numbers[i-1]==0:
                divisors.append([prime_numbers[i-1]])
                #divisors = divisors + prime_numbers[i-1]

            elif second_fraction_number%prime_numbers[i-1]==0:
                divisors.append([prime_numbers[i-1]])
                #divisors = divisors + prime_numbers[i-1]

        #mmc_number = operator.mul(divisors,1)



        mmc_number = 1

        divisors = (str(divisors).replace("[","").replace("]","").replace(",",""))
        print (divisors)

        len_div = len(divisors)
        #divisors = list(map(int,divisors))

        for i in range(0,len_div):



            if type((divisors[i])) == int:

                print("Test")

我知道我的代码有很多错误,因为我不知道怎么做......

我试过了:

print(reduce(operator.mul, divisors[]))

并且也没有用。

print(reduce(mul, map(int, divisors)))

两者都不是。

我需要的例子: 如果除数= [2,3,5],我需要mmc_number = 2 * 3 * 5

2 个答案:

答案 0 :(得分:3)

您只需在[]之后删除divisors

divisors = ["2","3","5"]
from operator import mul
print(reduce(mul, map(int, divisors)))   # 30

如果divisors is 2 5 7,您应该执行以下操作

divisors = "2 5 7"
from operator import mul
print(reduce(mul, map(int, divisors.split())))   # 70

答案 1 :(得分:0)

或许将它们从string转换为int是需要的:

divisors = [2,3,5]
from operator import mul
print(reduce(mul, int(divisors)))   # 30