gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:16:23 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com