如何在一行中重新编写此代码?

时间:2019-06-19 11:07:44

标签: python

是否有一种方法可以用不同于此的方式编写if-else语句?也许更短?

def __init__(self, attributes):
    self.attributes = attributes
    if "yes" in self.attributes:
        self.diabetes = "yes"
    elif "no" in self.attributes:
        self.diabetes = "no"
    else:
        self.diabetes = ""

3 个答案:

答案 0 :(得分:2)

尝试:

self.diabietes = 'yes' if 'yes' in attributes else 'no' if 'no' in attributes else ''

要进一步改善它,我们需要对attributes类型进行一些假设。

答案 1 :(得分:0)

另外两种方式:

self.diabetes = ('yes', 'no', '')[('yes' in attributes, 'no' in attributes, True).index(True)]

self.diabetes = [i for i in ('yes', 'no', '') if i in attributes][0]

答案 2 :(得分:-1)

def __init__(self, attributes):
    self.diabetes = ""
    if "yes" in attributes:self.diabetes = "yes"
    elif "no" in attributes:self.diabetes = "no"