Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在一行中重新编写此代码?_Python - Fatal编程技术网

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

Python 如何在一行中重新编写此代码?,python,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.diab

有没有一种方法可以用不同的方式编写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 = ""
尝试:

为了进一步改进,我们需要对
属性
类型进行一些假设。

还有两种方法:

def __init__(self, attributes):
    self.diabetes = ""
    if "yes" in attributes:self.diabetes = "yes"
    elif "no" in attributes:self.diabetes = "no"
self.diabetes = ('yes', 'no', '')[('yes' in attributes, 'no' in attributes, True).index(True)]


为什么代码必须在一行中?你只是想让它更难阅读。其实不需要一行,但任何其他的方式。谢谢!我以前试过,但没用。现在我知道错误在哪里了!self.diabetes=“是”如果self.attributes else self.diabetes=“否”如果self.attributes else self.attributes=“”中的“否”
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]