我想做下面的事情。我想要列表理解中条件表达式的输出。列表理解可以吗?
def why_bad(myvalue): #returns a list of reasons or an empty list it is good
...
return [ reason1, reason2 ..]
bad_values = [ (myvalue,reasons) for myvalue in all_values if (reasons = why_bad(myvalue)) ]
我想做下面的事情。我想要列表理解中条件表达式的输出。列表理解可以吗?
def why_bad(myvalue): #returns a list of reasons or an empty list it is good
...
return [ reason1, reason2 ..]
bad_values = [ (myvalue,reasons) for myvalue in all_values if (reasons = why_bad(myvalue)) ]
你可以像这样创建你的列表理解,它返回值及其原因(或一个空列表)为什么它不好:
def why_bad(value):
reasons = []
if value % 2:
reasons.append('not divisible by two')
return reasons
all_values = [1,2,3]
bad_values = [(i, why_bad(i)) for i in all_values]
print bad_values
为了扩展该示例,您可以为每个不同的条件检查添加 elifs,以了解为什么值不正确并将其添加到列表中。
回报:
[(1, ['not divisible by two']), (2, []), (3, ['not divisible by two'])]
但是,如果 all_values 只有唯一值,您可以考虑创建字典而不是列表推导:
>>> bad_values = dict([(i, why_bad(i)) for i in all_values])
>>> print bad_values
{1: ['not divisible by two'], 2: [], 3: ['not divisible by two']}
您可以使用嵌套列表推导:
bad_values = [value_tuple for value_tuple in
[(myvalue, why_bad(myvalue)) for myvalue in all_values]
if value_tuple[1]] # value_tuple[1] == why_bad(myvalue)
或使用filter
:
bad_values = filter(lambda value_tuple: value_tuple[1],
[(myvalue, why_bad(myvalue)) for myvalue in all_values])
不漂亮,但您可以尝试嵌套列表推导:
bad_values = [(v, reasons) for v in all_values
for reasons in [why_bad(v)] if reasons]