简体   繁体   English

如何在Python中使用三元运算符

[英]How to Use Ternary Operator in Python

I have this method: 我有这种方法:

def get_compression_settings(self, media_type=None):
        return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type))

Is there a way I can check if media_type == None and only append mediatypeid={0} if it is ~=None in a single line using a ternary operator? 有没有一种方法可以使用三进制运算符检查media_type == None,并且仅追加mediatypeid = {0}(如果〜= None)?

I know I could do the following, but it would nicer if my method could just be a single return: 我知道我可以执行以下操作,但是如果我的方法只能是一个返回值,那就更好了:

def get_compression_settings(self, media_type=None):
        endpoint = 'compression?mediatypeid={0}'.format(media_type) if media_type is not None else 'compression'
        return self.transmit('GET', endpoint)

It can be a single line return, as: 它可以是单行返回,如下所示:

return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type)
                             if media_type is not None else 'compression')

I split it onto multiple lines to improve readability, but that is not necessary for it to work. 我将其分成多行以提高可读性,但这对于它起作用不是必需的。 (Note that this required changing if media_type not none in your example to if media_type is not None ). (请注意, if media_type not none您的示例中的if media_type not noneif media_type not none需要将它更改为if media_type is not None )。

你有尝试过吗?

return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type) if media_type is not None else 'compression')

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

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