python - 如何使用 try 和 except 来防止 for 循环停止
问题描述
我有一堆样本是字典,其中一些值在列表中。我想从列表中检索信息,但有时列表中的某些键为空。我想要做的是检索某些值。我想声明,如果列表为空,则从不同的键中检索一个值。
我做了一个 if-elif 声明,但无法让它工作。我试图编写代码,如果 list==None 然后做一些事情 elif 做其他事情。似乎 None 不起作用。
我在下面举了一个我想要做的例子。
sample_1 = {'description' : {'captions': [],
'tags': ['person',
'cat']}}
sample_2 = {'description' : {'captions': ['NOT an empty list'],
'tags': ['person',
'cat']}}
# if captions list is empty then print first item in 'tags' list.
# else if the 'captions' list has an item then print that item
if sample_here['captions']==None in sample_here:
result = sample_here['description']['tags'][0]
elif 'captions' in sample_here:
result = sample_here['description']['captions'][0]
解决方案
空列表 [] 不等于 None。
sample_1 = {'description' : {'captions': [],
'tags': ['person',
'cat']}}
sample_2 = {'description' : {'captions': ['NOT an empty list'],
'tags': ['person',
'cat']}}
def get_captions(sample_here):
# thanks to bruno desthuilliers's correction. [] has a bool value False
if not sample_here['description']['captions']:
result = sample_here['description']['tags'][0]
else:
result = sample_here['description']['captions'][0]
return result
print(get_captions(sample_1))
print(get_captions(sample_2))
这输出:
person
NOT an empty list
推荐阅读
- base64 - Pronto 十六进制代码到 base64,如何转换
- python - Python - selenium - 单击选项卡
- vue.js - Vuex:双向绑定/反应性不起作用
- typescript - createBrowserHistory 的 push 方法可能不存在时出现 TypeScript 错误
- java - 太多的 if 语句
- rabbitmq - 陈旧的 rabbitmq 数据队列文件占用了磁盘
- python - scapy 在 windows/parrotsec (pycharm) 上不起作用
- node.js - Ethereiun Solidity Contract - 挂钩问题之前
- c++ - C ++中无序集的内部工作是什么?它使用什么算法?
- c# - 如何使用多个列表框组合格式化代码