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

2024-04-19 20:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: or函数in元素列表is整数year
3条回答

考虑到您正在尝试做的事情,我认为这是一种方法,将传递给函数的元素的for循环(以列表格式)与您所述的if-elif-else条件结合起来

years = ["25", "1955", "2000", "1581", "1321", "1285", "4365", "4", "1432", "3423", "9570"]
def isLeap(years):
    for i in years:
        if int(i) >= 1583:
            print(i, "Is a Gregorian Calendar Year.")
        elif int(i) < 1583:
            print(i, "Is not a Gregorian Calendar Year.")
        elif int(i) % 400 == 0 or int(years[i]) % 4 == 0:
            print(i, "Is a Leap Year.")
        elif int(i) % 400 == 1 or int(years[i]) % 4 == 1:
            print(i, "Is NOT a Leap Year.")
        else:
            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.

通过列表理解,可以简单地将字符串列表转换为整数列表:

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

代码中另一个明显的问题是理解变量的作用域并将参数传递给函数

如果您迭代了几年,那么将year项传递给您的函数并在函数的范围内使用

def isLeap(year):
...

for int_year in int_list:
    isLeap(int_year)

您应该在isLeap函数之外执行从字符串到int的转换:

for year in map(int, years):

函数应接受年份参数:

def isLeap(year)

你的测试应该是:if year >= 1583 # etc.

然而,这里也有一个逻辑问题:因为您使用的是if/elif,所以您永远不会确定某个事物是否是闰年,因为前两个if语句中的一个总是正确的(要么>;=1583年,或<;1583; 不会检查其他条件。)

相关问题 更多 >