[英]Python, append within a loop
So I need to save the results of a loop and I'm having some difficulty. 所以我需要保存循环的结果,但遇到了一些困难。 I want to record my results to a new list, but I get "string index out of range" and other errors.
我想将结果记录到新列表中,但是出现“字符串索引超出范围”和其他错误。 The end goal is to record the products of digits 1-5, 2-6, 3-7 etc, eventually keeping the highest product.
最终目标是记录1-5、2-6、3-7等数字的乘积,最终保持最高乘积。
def product_of_digits(number):
d= str(number)
for integer in d:
s = 0
k = []
while s < (len(d)):
j = (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 1
k.append(j)
print(k)
product_of_digits(n)
Similar question some time ago. 前段时间类似的问题。 Hi Chauxvive
嗨Chauxvive
This is because you are checking until the last index of d
as s
and then doing d[s+4]
and so on... Instead, you should change your while
loop to: 这是因为您要检查直到
d
的最后一个索引为s
,然后再进行d[s+4]
等等。相反,应将while
循环更改为:
while s < (len(d)-4):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.