Python 如何在一行中重新编写此代码?
有没有一种方法可以用不同的方式编写if-else语句?也许更短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
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]