は任意のPython的または以下のif
文を書くためのコンパクトな方法がある場合:簡素化ステートメントのpython
if head is None and tail is None:
print("Test")
ような何か:
if (head and tail) is None:
は任意のPython的または以下のif
文を書くためのコンパクトな方法がある場合:簡素化ステートメントのpython
if head is None and tail is None:
print("Test")
ような何か:
if (head and tail) is None:
head
とtail
両方がカスタムクラスのインスタンス(のようなNode()
ある場合似たような)長さやブール値がない場合は、次のようにしてください:
if not (head or tail):
エーテルhead
またはtail
が、false-y値(False
、数値0、空のコンテナなど)を持つNone
以外のオブジェクトである可能性がある場合は、これは機能しません。
それ以外の場合は、明示的なテストが必要です。ブール論理には「英語文法」のショートカットはありません。
注:値が真実でないことを確認します( 'None'値だけではない) –
'もしかしたら(頭や尾) '(または'頭と尾ではないならば) ' –
@KirillBulygin:今日はもっとカフェインが必要です。 –
ちなみに、(a and b) = 0
が数学で許可されていないのと同じ理由でプログラミングには許可されません(それぞれのステートメントに正式な形式が1つしかないようにするためには、事も "explicit Pythonのモットーです)。
どういう意味ですか? '(headとtail)is None'はPythonでは完全に有効ですが、それが期待することはしません。 :) –
私は確かに '(aとb)= 0'と同じ意図で書かれた'(頭と尾)は 'なしを意味します。 –
if head is None and tail is None:
print("Test")
は、明確で効率的です。どちらかhead
またはtail
はおそらくNone
から離れて偽っぽいの値を取ることができますが、あなたが唯一の彼らは両方None
をしているときを印刷する場合は、次に何を書いたことは、より安全よりも
if not (head or tail):
print("Test")
よりコンパクトなバージョンがありますまだ効率的で安全な&である(あなたのコードよりも)
if head is None is tail:
print("Test")
head is None is tail
が実際に(head is None) and (None is tail)
に相当しています。しかし、私はあなたの元のバージョンよりも読みにくいと思う。
ところで、(head and tail) is None
は有効なPythonの構文ですが、それは行いませんので、あなたが最初にそれを行う期待するかもしれないものを、お勧めしません:
from itertools import product
print('head, tail, head and tail, result')
for head, tail in product((None, 0, 1), repeat=2):
a = head and tail
print('{!s:>4} {!s:>4} {!s:>4} {!s:>5}'.format(head, tail, a, a is None))
出力
head, tail, head and tail, result
None None None True
None 0 None True
None 1 None True
0 None 0 False
0 0 0 False
0 1 0 False
1 None None True
1 0 0 False
1 1 1 False
あなたのコードはできるだけPythonに近いものです。
これらのことについては、The Zen of Pythonが時には簡単なことが最良の選択肢であることを覚えておくと役に立ちます。
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
etc...
いいえ、あなたがそれを書く方法です。妥当ではあるが偽の値がなければ(例えば '' '')、Martijnの提案で十分です。 – jonrsharpe
他の何らかの理由で値が誤っている可能性がない場合: '頭ではなく、尾ではない場合: ' –
' head'または 'tail'は他のfalse-ish値をとる可能性がありますか? –