猿问

无法将列表转换为整数并遍历列表

我正在努力弄清楚如何将列表转换为整数,并在每个元素上迭代一个函数。我希望该函数检查每个元素,并需要将列表中的每个元素转换为整数。


years = ["25", "1955", "2000", "1581", "1321", "1285", "4365", "4", "1432", "3423", "9570"]

def isLeap():

    year = list(map(int, years))

    if year in years >= 1583:

        print(year, "Is a Gregorian Calendar Year.")

    elif year in years < 1583:

        print(year, "Is not a Gregorian Calendar Year.")

    elif year in years % 400 == 0 or year in years % 4 == 0:

        print(year, "Is a Leap Year.")

    elif year in years % 400 == 1 or year in years % 4 == 1:

        print(year, "Is NOT a Leap Year.")

    else:

        print("Test cannot be performed.")

for i in years:

    isLeap()


慕尼黑的夜晚无繁华
浏览 101回答 3
3回答

蛊毒传说

鉴于您正在尝试做的事情,我相信这是一种方法,将for您传递给函数的元素的循环(以列表格式)与if-elif-else您陈述的条件相结合。years = ["25", "1955", "2000", "1581", "1321", "1285", "4365", "4", "1432", "3423", "9570"]def isLeap(years):&nbsp; &nbsp; for i in years:&nbsp; &nbsp; &nbsp; &nbsp; if int(i) >= 1583:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(i, "Is a Gregorian Calendar Year.")&nbsp; &nbsp; &nbsp; &nbsp; elif int(i) < 1583:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(i, "Is not a Gregorian Calendar Year.")&nbsp; &nbsp; &nbsp; &nbsp; elif int(i) % 400 == 0 or int(years[i]) % 4 == 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(i, "Is a Leap Year.")&nbsp; &nbsp; &nbsp; &nbsp; elif int(i) % 400 == 1 or int(years[i]) % 4 == 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(i, "Is NOT a Leap Year.")&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Test cannot be performed.")isLeap(years)输出:25 Is not a Gregorian Calendar Year.1955 Is a Gregorian Calendar Year.2000 Is a Gregorian Calendar Year.1581 Is not a Gregorian Calendar Year.1321 Is not a Gregorian Calendar Year.1285 Is not a Gregorian Calendar Year.4365 Is a Gregorian Calendar Year.4 Is not a Gregorian Calendar Year.1432 Is not a Gregorian Calendar Year.3423 Is a Gregorian Calendar Year.9570 Is a Gregorian Calendar Year.

繁花不似锦

您应该在isLeap函数之外进行从 string 到 int 的转换:for year in map(int, years):你的函数应该接受一个年份参数:def isLeap(year)你的测试应该是:if year >= 1583 # etc.但是,这里还有一个逻辑问题:因为您使用的是if/elif,所以您永远无法确定某事是否是闰年,因为您的前两个 if 语句中的一个总是正确的。(它要么 >= 1583,要么 < 1583;不会检查其他条件。)

哆啦的时光机

将字符串列表转换为整数列表可以通过列表推导简单地完成:int_list = [int(year) for year in years]代码中另一个明显的问题是理解变量的范围并将 args 传递给函数。如果您迭代多年,则将年份项目传递给您的函数并在函数范围内使用def isLeap(year):...for int_year in int_list:&nbsp; &nbsp; isLeap(int_year)
随时随地看视频慕课网APP

相关分类

Python
我要回答