Pergunta

I am trying to check if sent1 or sent2 has zero length and if they have i want to set sent_witn_not_null as the list with non-zero list. But the if-else conditions, i've written seems convoluted. What is a simpler way of doing this?

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
Foi útil?

Solução

Take advantage of Python's coalescing operators.

sent_with_not_null = sent2 and sent1

Outras dicas

Something like this?

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']

or:

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']
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top