2017-03-10 5 views
1

リストとして返すように評価され、私が書いた:リストは、ブールが、私は、Python(3.6)に新たなんだ

def foo(alist, blist): 
    if alist or blist: 
     return alist or blist 

print(foo([2], [])) 

[2]を印刷しています。

と私は理解しようとしている:リストがif alist or blistTrue \ Falseに評価されていることのように思えるが、return alist or blistには、リスト自体ではなくTrue \ Falseを返します。どのようだ?

alist or blistは、2つの空でないリストに評価されますか?すべてのためのドキュメントのどこかに書かれたルールはありますか?

おかげ

答えて

3

最初のリスト[2]ブール文脈でFalseである第二空のリスト[]に反対True値と考えられます。

以下の値が偽であると考えられる: ....

任意の空のシーケンス、例えば、 ''、()、[]


x or y xが偽である場合、Y、他X

これは最初のものが偽であればそれだけで2番目の引数が評価され、短絡演算子であります

チェックdocs


通訳から:

>>> ['test'] or [] 
['test'] 
>>> 
>>> ['test'] or ['test2'] 
['test'] 
>>> 
>>> [] or ['test2'] 
['test2'] 
>>> 
>>> [] or [] 
[] 
+0

と 'リターン連想リストやblist'で?それは空でないものに評価されますか? –

+0

は、_non-empty_リストが真実であるということはそれ以上はありませんか?例えば、 'foo([2]、[4])'を呼んだ場合、 "空リストの振る舞い"はありません - 真理のために '[2]'が返されます – asongtoruin

+0

'xがfalseならy、else x'それが '[2]' return - > 'else x'の理由です。もちろん、空ではないリストは* True * @ason​​gtoruin – klashxx

1

コードを理解するために、コメントコードをチェックしてください:

def foo(alist, blist): 
    if alist or blist: 

     #this if condition checks if alist is empty or blist is empty 
     # Means: in actual this condition will be like this 
     if alist != None or blist != None 
     #None means if the list is empty or not 

     return alist or blist 

     # it returns the non-empty list just like the above explanation 
     # If both lists have some values then it will always return the first list which is alist 

print(foo([2], [])) 
# Try you code with following statements to understand it 

print(foo([], [])) 
# You will get None 

print(foo([2], [3])) 
# You will get [2] 

print(foo([2], [2,4,5])) 
# You will get [2] 

print(foo([], [3])) 
# You will get [3] 
関連する問題