简体   繁体   English

为什么我不能在 python 生成器表达式中使用“else”(来自 if / else)?

[英]Why can I not have `else` (from if / else) with python generator expressions?

I have the following code, which works fine:我有以下代码,它工作正常:

incl_list = ['A']
my_list = [{'A': 1, 'B': 'world'}, {'A': 4, 'B': 'hello'}]
result = '\n'.join(','.join(f'{key}={value}' for key, value in record.items() if key in incl_list) for record in my_list)

The result yields:结果产生:

'A=1\nA=4'

My question is why can I not add an else statement, like so:我的问题是为什么我不能添加else语句,如下所示:

result = '\n'.join(','.join(f'{key}={value}' for key, value in record.items() if key in incl_list) else 'ignore' for record in my_list)

similar to list-comprehension?类似于列表理解?

The error I get is:我得到的错误是:

 File "<ipython-input-276-201c8f88ac13>", line 1
    result = '\n'.join(','.join(f'{key}={value}' for key, value in record.items() if key in incl_list else 'ignore') for record in my_list)
                                                                                                         ^
SyntaxError: invalid syntax

Your else statement needs to go together with an if statement, when using inside a comprehension, thus you could modify your code like so to make it work你的else语句需要 go 和一个if语句,在理解中使用时,因此你可以像这样修改你的代码以使其工作

result = '\n'.join(','.join(f'{key}={value}' if key in incl_list else 'ignore' for key, value in record.items()) for record in my_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM