Python 嵌套列表理解:if/for,而不是for/if

Python 嵌套列表理解:if/for,而不是for/if,python,python-2.7,Python,Python 2.7,如何创建这样的嵌套列表: 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时遍历列表。对于列表理解,这可能吗 编辑0: 我现在拥有的:dl

如何创建这样的嵌套列表:

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
时遍历列表。对于列表理解,这可能吗

编辑0:

我现在拥有的:
dl=[str(d.get('title'))代表info.get('director')[0:10]]

  • info
    是一个IMDbPy Person对象,其作用类似于字典(键和值)
  • director
    有时不存在,这就是我想测试的
    None
  • 如果
    director
    确实存在,它应该返回IMDbPy电影对象的列表(也带有键和值),这就是我得到的
    标题
  • 它应该返回一个字符串列表,或者一个包含一个元素的列表:字符串“None”
编辑1:

测试用例:

# 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\u comp
应该给出
['1','2']
list\u comp1
应该给出
['None']
我之前的评论:

以下表达式的计算结果应符合您的要求(如果您在dict中包含
'h1'
的引号):


列表理解的目的是创建一个新的列表。您是否正在尝试创建一个?如果不满足条件,您希望结果是什么?如果blah:someList=[f(i)for i in blah],你可以做
if blah:someList=[f(i)for i in blah]
。如果dict.get(key)不是其他[“None”],
[f(i)for i in dict.get(key)],如果dict.get(key)不是其他[“None”]
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']