for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item['id']
count_ret = item['retweet_count']
如果item['id']
抛出KeyError
异常,则执行终止。
如何使for
循环在异常后继续执行?
答案 0 :(得分:5)
您可以尝试捕获引发的KeyError
异常,然后将其丢弃:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
try:
id_twitty = item['id']
count_ret = item['retweet_count']
except KeyError:
pass
答案 1 :(得分:4)
除EAFP
样式外,如果LBYL
中找不到id
,您可以应用item
并使用continue
:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
elif 'id' not in item:
continue
else:
id_twitty = item['id']
count_ret = item['retweet_count']
答案 2 :(得分:1)
如果item['id']
存在,您可以先检查:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
if 'id' in item:
id_twitty = item['id']
count_ret = item['retweet_count']
如果不存在,请使用None
:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item.get('id')
count_ret = item['retweet_count']
如果不存在,请使用其他默认值:
default_id = 0
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item.get('id', default_id)
count_ret = item['retweet_count']
答案 3 :(得分:1)
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item.get('id', None)
count_ret = item.get('retweet_count', None)
if not id_twitty or not count_ret:
print "could not retrieve id or count"
# handle error here