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()
解决方案
将字符串列表转换为整数列表可以通过列表推导简单地完成:
int_list = [int(year) for year in years]
代码中另一个明显的问题是理解变量的范围并将 args 传递给函数。
如果您迭代多年,则将年份项目传递给您的函数并在函数范围内使用
def isLeap(year):
...
for int_year in int_list:
isLeap(int_year)
推荐阅读
- bash - How to compare filenames in bash
- c - 嵌套在 for 循环中的 fprintf 不写入第一个元素
- jquery - JSON Parse error when posting to MEAN API
- ruby - 为什么我的除法运算符一直返回零?
- esp8266 - .lua are deleted when trying to copy nodemcu from one ESP8266 to another
- python - 循环 .csv 文件并删除任何非 ascii 字符串
- java - 如何为用户输入的次数迭代for循环Java
- javascript - ConstraintError:对象存储中已存在密钥
- python-3.x - 如何保存为 PNG 到 tkinter 的图像(企鹅)
- npm - NPM安装错误?发现漏洞