Python 3.x 如何跳过任何不在for循环范围内的值
我试图创建3个嵌套的for循环,并跳过任何for循环中没有的值。我尝试过不同的方法,但还没有取得多大成功。以下是for循环的示例:Python 3.x 如何跳过任何不在for循环范围内的值,python-3.x,Python 3.x,我试图创建3个嵌套的for循环,并跳过任何for循环中没有的值。我尝试过不同的方法,但还没有取得多大成功。以下是for循环的示例: for industry in string.ascii_uppercase: for code in range(1, 99): for year in range(1998, 2019): createCSV(industry, code, year) 问题是有些行业和代码值的数据不可用。代码在代码=3处中断,因
for industry in string.ascii_uppercase:
for code in range(1, 99):
for year in range(1998, 2019):
createCSV(industry, code, year)
问题是有些行业和代码值的数据不可用。代码在代码=3处中断,因为变量代码的原始值中缺少3。如果只有一个值,我可以使用continue跳过它
for industry in string.ascii_uppercase:
for code in range(1, 99):
if code == 3:
continue
for year in range(1998, 2019):
createCSV(industry, code, year)
但是,行业和代码都有更多的价值缺失,我正试图找到一种有效的方法。谢谢您的帮助。您可以查看:
一种可能的方法是使用以下条款: 在其中,您仍然可以使用您的
createCSV
函数引发的特定异常类替换通用的异常。例如,如果您知道当作为输入参数提供无效的code
值时,createCSV
将引发ValueError
,则将Exception:
替换为Exception ValueError:
。这将有助于避免一些潜在的陷阱(有关更多信息,请参阅)
但是,如果可能的话,我建议:
- 事先只使用有效的
code
值检索iterable,然后只循环这些值,或者
- 修改
createCSV
的编程代码,使其在提供无效的code
值时不会中断
如果您已经知道哪些值会导致错误,请避免在这些值上循环
missing_code_values=[3,4,5,6,7,83]
missing_ascii_values=['A','Z']
for industry in [x for x in string.ascii_uppercase if x not in missing_ascii_values]:
for code in [x for x in range(1, 99) if x not in missing_code_values]:
for year in range(1998, 2019):
createCSV(industry, code, year)
如果您不知道,那么可以使用try/except
for industry in string.ascii_uppercase:
for code in range(1, 99):
for year in range(1998, 2019):
try:
createCSV(industry, code, year)
except: # mention specific exception if you can
print("Skipping Industry-",industry," Code-",code," Year-",year)
您可能需要一个try
和except
语句。听起来您很清楚哪些值是无效的,那么为什么不将它们存储在集合
中,然后在循环时检查包含?您提前知道哪些值是有效的/无效的吗?@pstatix和Carciagenicate我不知道缺少哪些值,但我可以想想看。但是,这需要时间,而且缺少的列表太长,因此我正在寻找一种更有效的方法来实现这一点。这不会起作用,因为在迭代范围时,code
不会是None
。OP表示他们知道需要跳过哪些值,而不是测试是否为空。
missing_code_values=[3,4,5,6,7,83]
missing_ascii_values=['A','Z']
for industry in [x for x in string.ascii_uppercase if x not in missing_ascii_values]:
for code in [x for x in range(1, 99) if x not in missing_code_values]:
for year in range(1998, 2019):
createCSV(industry, code, year)
for industry in string.ascii_uppercase:
for code in range(1, 99):
for year in range(1998, 2019):
try:
createCSV(industry, code, year)
except: # mention specific exception if you can
print("Skipping Industry-",industry," Code-",code," Year-",year)