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

时间:2013-01-28 03:42:00

标签: python if-statement convolution ternary

我正在尝试检查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 个答案:

答案 0 :(得分:1)

利用Python的合并运算符

sent_with_not_null = sent2 and sent1

答案 1 :(得分: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']