python - python 初学者 - 数字的倍数(有限制)

标签 python multiplication

我正在尝试弄清楚如何在 python 中将数字相乘,但遇到了一些麻烦。

程序应该像这样运行:

Multiple of: 2 (for example)  
Enter an upper limit: 10  
[2, 4, 6, 8, 10]  
The product of the list [2, 4, 6, 8, 10] is: 3840 (this has to be in a separate function and work for any integer)
<小时/>
n = int(input("Multiples of: "))
l = int(input("Upper Limit: "))

def calculation():
    for x in range(0, l):
        c = x * n
        mylist = [c]
        print(mylist, end=' ')

    calculation()

def listfunction():
    productlist = []
    for r in productlist:
        productlist = [n * l]
        print(productlist)


listfunction()

第一个问题是,当它运行时,它创建了多个指定的l变量,格式也格式化不同,即[1] [2] [3]而不是[1, 2, 3]

第二部分我真的不知道如何去做。我认为它会类似于我上面的内容,但它什么也没返回。

最佳答案

the format is also formatted differently, ie [1] [2] [3] instead of [1, 2, 3]

这是因为你的循环每次都会创建一个包含一个变量的列表:

for x in range(0, l):            # the '0' is redundant. You can write just "for x in range(l):"
    c = x * n                    # c is calculated
    mylist = [c]                 # mylist is now [c]
    print(mylist, end=' ')       # print mylist

相反,在循环之前声明列表,并在循环内部向其中添加元素:

mylist = []
for x in range(l):
    c = x * n                    # c is calculated
    mylist.append(c)             # mylist is now mylist + [c]
print(mylist, end=' ')           # print mylist
<小时/>

The second part I don't really have an idea on how to do it. I thought it would be similar to what I have like above, but it returns nothing.

其实是一样的...

您应该初始化一个数字product = 1并将其乘以列表中的每个数字:

product = 1                            # no need for list, just a number
for r in productlist:                  
    product = product * r              # or product *= r     
    print(product )
<小时/>

顺便说一句,无需重新发明轮子...您可以通过以下方式获取列表的乘积:

from functools import reduce  # needed on Python3
from operator import mul
list = [2, 4, 6, 8, 10]  
print(reduce(mul, list, 1))

关于python - python 初学者 - 数字的倍数(有限制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963984/

相关文章:

python - pandas 系列元素明智乘法

java - 欧拉计划 #11

python - dict 追加键和值的列表

python - 如何创建处理多项式的函数?

python Pandas : Modify Dataframe with mask and create new Dataframe

python - 如何修复 '%' 处或附近的 psycopg2 语法错误?

在两个大整数相乘期间捕获并计算溢出

c# - 除法和乘以相同数字时表达式上的 Math.Ceiling()

python - django 中的 Endblock 标记无效

Python:如何存储可变变量(例如集合)?