0

send1またはsent2の長さがゼロであるかどうか、およびゼロ以外のリストを含むリストとして設定 する必要があるかどうかを確認しようとしています。しかし、if-else条件、私が書いたのは複雑なようです。これを行う簡単な方法は何ですか?sent_witn_not_null

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
4

2 に答える 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']
于 2013-01-28T03:50:12.037 に答える
1

Pythonの合体演算子を利用します。

sent_with_not_null = sent2 and sent1
于 2013-01-28T03:44:25.290 に答える