繁体   English   中英

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

[英]How to append result from the loop into array every time it iterates in python

我一直在从事此程序的工作,将不胜感激。
程序以查找两年之间的the年并将其添加到数组中...

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])

移动n个第一项任务外循环和更换whilefor 就像是

n=array('i') # or you can use smthg like n=[]
for i in range(i,2018):
    if i%4==0:
        n.append(i)

此外,您的leap年考试不正确。 从维基:

可以精确地除以4的每一年都是a年,除非可以精确地除以100的年份,但是如果可以将其精确地除以400的年份,则这些百年就是leap年。例如,1700、1800和1900年是不是leap年,而是1600年和2000年。 闰年

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM