麻烦将列表转换为整数并遍历列表

时间:2019-10-03 18:07:12

标签: python function loops integer

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

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

3 个答案:

答案 0 :(得分:0)

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

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

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

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

def isLeap(year):
...

for int_year in int_list:
    isLeap(int_year)

答案 1 :(得分:0)

鉴于您要尝试执行的操作,我相信这是一种实现方法,将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.

答案 2 :(得分:0)

您应该在A函数之外进行从字符串到整数的转换:

isLeap

您的函数应接受年份参数:

for year in map(int, years):

您的测试应该只是:def isLeap(year)

但是,这里还存在一个逻辑问题:因为您使用的是if year >= 1583 # etc.,所以您将永远无法确定某事是否是a年,因为前两个if语句之一始终是正确的。 (它是> = 1583,或者是<1583;将不会检查其他条件。)