gpt4 book ai didi

python - 每次在python中迭代时如何将循环结果附加到数组中

转载 作者:太空宇宙 更新时间:2023-11-04 07:57:55 25 4
gpt4 key购买 nike

我一直在研究这个程序,任何形式的帮助都将不胜感激。
查找两年之间的闰年并将其添加到数组中的程序...

from array import array

x=int(input("Enter the year "))
print("the year you entered is",x)

while x<=2017:
if x%4==0:
print(x)
n=array('i',[x])
n.append(x)
x=x+1
else:
x=x+1
print(n)

输出

enter the year 1992
the year you entered is 1992
1992
1996
2000
2004
2008
2012
2016
array('i', [2016, 2016])

最佳答案

问题是每当一年被 4 整除时,您都会重新设置数组的值。您要做的是在循环外声明数组。

from array import array

x=int(input("enter the year from which you want to know the leap year from"))
print("the year you entered is",x)

n=array('i')
while x<=2017:
if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0:
print(x)
n.append(x)
x += 1 # we need to add 1 regardless, no need for else
print(n)
# output: array('i', [1992, 1996, 2000, 2004, 2008, 2012, 2016])

关于python - 每次在python中迭代时如何将循环结果附加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45529144/

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