如何捕获 Python 中的特定索引错误并为此附加新值?
How to catch specific index error in Python and attach new value for this?
我想 return None 仅当我发现索引超出问题值的范围时
def extract_values(values):
try:
first = values[0]
second = values[1]
last = values[3]
except IndexError:
first = "None"
last = "None"
second = "None"
return first,second,last
# test
list_values = ["a","b","c"]
print(extract_values(list_values))
actual result with this code :
('None', 'None', 'None')
missed result :
('a', 'b', 'None')
肯定有一个更优雅的答案,但你可以这样做:
def extract_values(values):
try:
first = values[0]
except IndexError:
first = None
try:
second = values[1]
except IndexError:
second = None
try:
third = values[3]
except IndexError:
third = None
return first, second, third
我想 return None 仅当我发现索引超出问题值的范围时
def extract_values(values):
try:
first = values[0]
second = values[1]
last = values[3]
except IndexError:
first = "None"
last = "None"
second = "None"
return first,second,last
# test
list_values = ["a","b","c"]
print(extract_values(list_values))
actual result with this code :
('None', 'None', 'None')
missed result :
('a', 'b', 'None')
肯定有一个更优雅的答案,但你可以这样做:
def extract_values(values):
try:
first = values[0]
except IndexError:
first = None
try:
second = values[1]
except IndexError:
second = None
try:
third = values[3]
except IndexError:
third = None
return first, second, third