2016-05-03 4 views
3

私は辞書のリストを持っています。空の値を比較するのが効果がないのはなぜですか?

students = [{"id":''},{"id":1},{"id":3}] 

私はこれを繰り返して、idが''ではない辞書を探しています。

for student in students: 
    if(student['id'] is not None or student['id'] != ''): 
     print("found student" + str(student['id'])) 
     break 

しかし、それは常にifブロック内で何が起こるのか、関係なく:ここ

は、私がしようとしているものです。空白の値を比較する際に間違っているポインタはありますか?

+4

"and"ではありませんか? –

+0

ああ!それは私の非常に愚かだった:)私は第1条件 'を除いたif(student ['id']!= '')'これは十分だった!ありがとう – aaj

答えて

4

のように、値を取得する前に辞書に存在している場合でも確認できます。

if student['id'] not in (None, ''): 
    # do someting 
3
student['id'] is not None or student['id'] != '' 
  • 値が実際None場合None''と等しくないように、第2の条件は、真であろう。

  • 値が空の場合、最初の条件は真になります。空ではないのはNoneではありません。

or演算子は、式の少なくとも一方がTruthyであることを必要とするので、この式全体が常にTrueになります。そのため、コントロールは常にブロックifに入ります。


ここでDe Morgan's lawsを使用できます。あなたが欲しい

"not (A and B)" is the same as "(not A) or (not B)" 

also, 

"not (A or B)" is the same as "(not A) and (not B)". 

あなたは

if student['id'] is not None and student['id'] != '': 
    # print details 

または

if not (student['id'] is None or student['id'] == ''): 
    # print details 

、と同じように書かれていることができるように、IDは、 "ないなし" と "空でない" ことがないように

代わりに、私はこのように慣用的に書くことをお勧めします。

for student in students: 
    if student['id']: 
     # print details 

値がNoneまたは空の場合、ifステートメントは現在のオブジェクトをスキップします。 idがTruthy値の場合にのみ、詳細が出力されます。


idは何については、この

for student in students: 
    if 'id' in student and student['id']: 
     # print details 
0
if(person is not theif or person is not king): 
    kings and theif are both allowed into the closure. 
    as kings are not thief and thief are not king. 

or操作のみ満足するにはone true conditionが必要です。物には1つのタイプしかありません。

One type will always not be at least one two different things. 
+0

このコードは質問に答えるかもしれませんが、理由や質問にどのように回答するかについての追加の文脈を提供することで、長期的な価値が大幅に向上します。あなたの答えを[編集]して、説明を加えてください。 – CodeMouse92

関連する問題