简化复杂的if-else条件检查len(list)=0 - Python

0 投票
2 回答
593 浏览
提问于 2025-04-17 13:53

我想检查一下 sent1 或 sent2 是否为空,也就是长度为零。如果它们有空的情况,我想把 sent_witn_not_null 设置为一个包含非空内容的列表。但是我写的 if-else 条件看起来有点复杂。有没有更简单的方法来实现这个?

sent1 = ["this","is","foo","bar"]
sent2 = []

if len(sent1) or len(sent2) == 0:
    sent_with_not_null = sent2 if len(sent1) == 0 else sent1
    sent_with_not_null = sent1 if len(sent2) == 0 else sent2

2 个回答

1

像这样吗?

In [4]: if sent1 or sent2:
    sent_with_not_null=sent1 if sent1 else sent2
   ...:     

In [5]: sent_with_not_null
Out[5]: ['this', 'is', 'foo', 'bar']

或者:

In [11]: if any((sent1,sent2)): #in case both sent1 and sent2 are len==0

    sent_with_not_null =sent1 or sent2   #set the first True item to sent_with_not_null 
                                         #else the last one
   ....:     

In [12]: sent_with_not_null
Out[12]: ['this', 'is', 'foo', 'bar']
1

利用Python的合并运算符

sent_with_not_null = sent2 and sent1

撰写回答