我想做类似下面的事情。我想在列表推导中输出条件表达式。是否可以使用列表理解?
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)) ]
答案 0 :(得分:1)
你可以像这样创建你的列表理解,它返回值及其原因(或一个空列表),说明它为什么不好:
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
要扩展示例,您可以为每个不同的条件检查添加elif,以查找值为坏的原因并将其添加到列表中。
返回值:
[(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']}
答案 1 :(得分:0)
您可以使用嵌套列表解析:
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])
答案 2 :(得分:0)
不漂亮,但您可以尝试嵌套列表推导:
bad_values = [(v, reasons) for v in all_values
for reasons in [why_bad(v)] if reasons]