首页 > 解决方案 > 无法将列表转换为整数并遍历列表

问题描述

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

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

标签: pythonfunctionloopsinteger

解决方案


将字符串列表转换为整数列表可以通过列表推导简单地完成:

int_list = [int(year) for year in years]

代码中另一个明显的问题是理解变量的范围并将 args 传递给函数。

如果您迭代多年,则将年份项目传递给您的函数并在函数范围内使用

def isLeap(year):
...

for int_year in int_list:
    isLeap(int_year)

推荐阅读