如何创建这样的嵌套列表解析:
if (dict.get(key) != None):
for i in dict.get(key):
#expression
而不是:
for i in dict.get(key):
if (dict.get(key) != None):
#expression
(dict.get(key)将给出一个列表或没有)
实质上,只有当密钥的值不是None
时,我才想遍历列表。列表推导这可能吗?
EDIT0:
我现在拥有的内容:dl = [str(d.get('title')) for d in info.get('director')[0:10]]
info
是一个IMDbPy Person对象,其作用类似于字典(键和值)director
有时不存在,这就是我想要测试的None
director
确实存在,它应该返回一个IMDbPy Movie对象列表(也包含键和值),这就是我得到的title
EDIT1:
测试用例:
# this should work, as the key exists
my_dict = {'name': 'Bob', 'age': 40, 'times': [{h1: 1, m1: 1, h2: 0, m2: 59}, {h1: 2, m1: 3, h2: 2, m2: 57}]}
list_comp = [str(x.get('h1')) for x in my_dict.get('times')]
# but what if I try to get a value for a non-existent key?
list_comp1 = [str(x.get('h1')) for x in my_dict.get('time')]
my_dict.get('time')
将返回NoneType
个对象,但我该如何检测到它?
list_comp
应该['1', '2']
而list_comp1
应该['None']
答案 0 :(得分:1)
来自我之前的评论:
以下表达式应评估您的要求(如果您在词典中包含'h1'
周围的引号):
list_comp = [str(x.get('h1')) for x in my_dict.get('times')]
if my_dict.get('times') is not None else ['None']
list_comp1 = [str(x.get('h1')) for x in my_dict.get('time')]
if my_dict.get('time') is not None else ['None']