简体   繁体   English

仅在 Python 中没有 null 时打印 - 单行方法?

[英]Print only if not null in Python - one-line method?

I have a class object, Task , with four properties, t , date , priority and checked .我有一个 class object, Task ,有四个属性, tdateprioritychecked Only t must contain a value, the other three properties are optional.只有t必须包含一个值,其他三个属性是可选的。 I've written a print method which will print the strings if they're not null:我编写了一个打印方法,如果它们不是 null,它将打印字符串:

class Task:
    def __init__(self, _t, _date=None, _priority=None, _checked=False):
        self.t = _t
        try:
            self.date = parser.parse(_date, dayfirst=True) if _date else None
        except:
            self.date = None
        self.priority = _priority
        self.checked = _checked

    def print(self):
        print(self.t, end="")
        if self.date:
            print(self.date, end="")
        if self.priority:
            print(self.priority, end="")

... But I was wondering if there's a way of compressing this into a single line. ...但我想知道是否有办法将其压缩成一行。 In VB.NET, you can do something like this:在 VB.NET 中,您可以执行以下操作:

Console.Writeline(me.t, If(me.date Is Not Nothing, me.date, ""), If(me.priority Is Not Nothing, me.priority, ""))

I tried doing this in Python something like below, but it doesn't work the same way:我尝试在 Python 中执行此操作,如下所示,但它的工作方式不同:

print(self.t, if(self.date, self.date), if(self.priority, self.priority))

Is there a one-line solution, or any neater way?有没有一条线的解决方案,或者任何更简洁的方法?

You can use filter with None or bool and by that to avoid printing None values您可以将filterNonebool一起使用,以避免打印None

def print(self):    
    print(*filter(None, [self.t, self.date, self.priority]))

Or或者

def print(self):    
    print(*filter(bool, [self.t, self.date, self.priority]))

You could create a list and then check if the list is not None :您可以创建一个列表,然后检查该列表是否不是None

class Task:
    def __init__(self, _t, _date=None, _priority=None, _checked=False):
        self.t = _t
        try:
            self.date = parser.parse(_date, dayfirst=True) if _date else None
        except:
            self.date = None
        self.priority = _priority
        self.checked = _checked
        self.print_list = [_t, _date, _priority]

    def print(self):
        [print(i, end=' ') for i in self.print_list if i is not None]

t = Task(_t=4, _date=25)
t.print()

A list comprehension for each variable that is not None :每个is not None的变量的列表推导:

def print(self):
        [print(i, end=' ') for i in self.print_list if i is not None]

Also equivalent:也等价:

def print(self): print(*[i for i in self.print_list if i is not None], end="")

Possibly even do the two birds one stone with a dict甚至可能用dict把两只鸟一块石头

class Task:
    def __init__(self, _t, _date=None, _priority=None, _checked=False):
        try:
            temp_date = parser.parse(_date, dayfirst=True) if _date else None
        except:    # I suggest making the except capture a more specific case
            temp_date = None
        self.entities = {'t': _t, 'date': temp_date, 'priority': _priority}

    def print(self): print([v for _, v in self.entities.items() if v is not None], end="")

t = Task(_t=4, _date=25)
t.print()

You can concatenate them and print, this will take care of the nulls:您可以连接它们并打印,这将处理空值:

def print(self):
    string= self.t + " " + self.date + " " + self.priority
    print(string,end = "")

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

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