簡體   English   中英

僅在 Python 中沒有 null 時打印 - 單行方法?

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

我有一個 class object, Task ,有四個屬性, tdateprioritychecked 只有t必須包含一個值,其他三個屬性是可選的。 我編寫了一個打印方法,如果它們不是 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="")

...但我想知道是否有辦法將其壓縮成一行。 在 VB.NET 中,您可以執行以下操作:

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

我嘗試在 Python 中執行此操作,如下所示,但它的工作方式不同:

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

有沒有一條線的解決方案,或者任何更簡潔的方法?

您可以將filterNonebool一起使用,以避免打印None

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

或者

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

您可以創建一個列表,然后檢查該列表是否不是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()

每個is not None的變量的列表推導:

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

也等價:

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

甚至可能用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()

您可以連接它們並打印,這將處理空值:

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