嵌套列表推导:if / for,not for / if

时间:2014-05-27 00:31:38

标签: 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时,我才想遍历列表。列表推导这可能吗?

EDIT0:

我现在拥有的内容:dl = [str(d.get('title')) for d in info.get('director')[0:10]]

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

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']

1 个答案:

答案 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']