在Python 3中,我有一个编码如下的程序。它基本上接受来自用户的输入并根据字典(EXCHANGE_DATA)进行检查并输出信息列表。
from shares import EXCHANGE_DATA
portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= portfolio_str.upper()
portfolio_list= portfolio_str.split(',')
print()
print('{:<6} {:<20} {:>8}'.format('Code', 'Name', 'Price'))
EXCHANGE_DATA = {code:(share_name,share_value) for code, share_name, share_value in EXCHANGE_DATA}
try:
for code in portfolio_list:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value))
except KeyError:
pass
示例输入:
GPG,HNZ,DIL,FRE
输出如下:
Please list portfolio: GPG,HNZ,DIL,FRE
Code Name Price
GPG Guinnesspeat 2.32
HNZ Heartland Nz 3.85
DIL Diligent 5.30
FRE Freightway 6.71
但如果我有一个输入:
AIR,HNZ,AAX,DIL,AZX
字词AAX,AZX
中不存在术语(EXCHANGE_DATA)
,但AIR,HNZ,DIL
这两个术语不存在。该程序显然会引发KeyError
异常,但我已用pass
中断了此异常。问题是在执行pass
代码后程序退出,我需要它继续执行并在for
上执行DIL
循环。我该怎么做?
答案 0 :(得分:20)
为什么不:
for code in portfolio_list:
try:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value)
except KeyError:
continue
或检查dict.get方法:
for code in portfolio_list:
res = EXCHANGE_DATA.get(code, None)
if res:
print('{:<6} {:<20} {:>8.2f}'.format(code, *res)
正如@RedBaron所说:
for code in portfolio_list:
if code in EXCHANGE_DATA:
print('{:<6} {:<20} {:>8.2f}'.format(code, *EXCHANGE_DATA[code])
答案 1 :(得分:4)
在循环中捕获异常
for code in portfolio_list:
try:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value)
except KeyError:
pass
编辑:测试dict是否具有第一个元素的更加pythonic方式
for code in portfolio_list:
if code in EXCHANGE_DATA:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value)
答案 2 :(得分:1)
您只需将try
/ except
块移动到for循环中。