每行打印一定数量

时间:2018-10-23 20:29:53

标签: python-3.x

我有这个问题需要解决,但是事实证明这很困难,而且我不知道哪里出了问题。我不知道我需要写些什么才能使每行仅打印10年。 到目前为止,我的代码如下 def main():

leap_start = int(input("Enter a start year: "))
leap_end = int(input("Enter an end year: "))

print("Here is a list of leap years between", leap_start,"and",leap_end, ":" )

for year in range(leap_start, leap_end):

    if (year% 400) !=0 and (year % 1000 == 0) and (year % 4) == 0:
     print ("", end = "")

    elif (year % 4) == 0:
        print (start, end = ",")

    elif (year % 100) == 0 and (year % 400) == 0:
        print (start, end =",")

    for y in range ((len(years)// 10) + 1):
         pri = years [10*y:(y+10) + 10]
         print(*pri, sep = ",")

    else :
      print ("", end = ",")

2 个答案:

答案 0 :(得分:0)

根据Mark的建议,我提出了一个不同的想法:

在每个leap年打印输出时,请在此巨大的for循环内设置一个从1到10的计数器,一旦您击中10,就重置为1并打印新行。否则,请用逗号和空格分隔每个项目。希望这个想法也能奏效。

答案 1 :(得分:0)

您解决了输入部分:

leap_start = int(input("Enter a start year: "))
leap_end = int(input("Enter an end year: "))     # this year is NOT checked 
                                                 # add 1 to if if you want it checked

print("Here is a list of leap years between", leap_start,"and",leap_end, ":" )

您可以定义一个方法,如果年份是a年则返回:

def isLeap(y):
    """Leap years are divisible by 4 but not by 100 unless they are divisible by 400"""
    return y % 4 == 0 and not y % 100 == 0 or y % 400 == 0

您从所有属于leap年的年份的范围中进行过滤(范围不会检查leap_end本身-如果需要同时对其加1):

years = [y for y in range(leap_start,leap_end) if isLeap(y)]

您将列表划分为最多10个项目的子列表(part),并将每个子列表打印在一行上。

for part in ( years[i:i+10] for i in range(0,len(years),10) ):
    # unpack the list into its 10 elements - print using a seperator of ','
    print(*part, sep=",")

Doku:

输出:

Enter a start year: 1899
Enter an end year: 2001
Here is a list of leap years between 1899 and 2001 :
1904,1908,1912,1916,1920,1924,1928,1932,1936,1940
1944,1948,1952,1956,1960,1964,1968,1972,1976,1980
1984,1988,1992,1996,2000