Idiomatic Pythonに関する質問があります - ゼロをチェックしていますが、この質問は条件内の変数のタイプもチェックすることを考慮してください。
スタイル0 if not variable else variable
ステートメントを指定すると、null オブジェクトがすり抜けます。
>>> x, y = None, []
>>> 0 if not(x and y) else x / y
0
>>> x, y = None, 0
>>> 0 if not(x and y) else x / y
0
>>> x, y = 0, 1
>>> 0 if not(x and y) else x / y
0
>>> x, y = 2, ""
>>> 0 if not(x and y) else x / y
0
>>> x, y = 2, 1
>>> 0 if not(x and y) else x / y
2
ただし、変数の値がゼロであることを明示的に確認すると、両方の型が異なる場合、またはゼロ値と比較できない型の場合にエラーが発生するため、多少良くなります。
>>> x, y = 2, ""
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'int' and 'str'
>>> x,y = "",""
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
>>> x,y = [],[]
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'list' and 'list'
通常、数値をチェックする条件を定義するとき、コードのようなものは0 if (x|y) == 0 else x/y
よりPythonic/より適切ですか?
ただし、ブール型がすり抜けて、次のような非常に厄介なことが発生するため、問題もありZeroDivisionError
ますValueError
。
>>> x,y = True, True
>>> 0 if (x&y) == 0 else x / y
1
>>> x,y = True, False
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> x,y = False, True
>>> 0 if (x&y) == 0 else x / y
0
>>> x,y = False, True
>>> 0 if (x&y) == 0 else math.log(x/y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
また、変数のタイプが数値であるが多少異なる場合、これは問題を引き起こします。
>>> x, y = 1, 3.
>>> 0 if (x|y) == 0 else math.log(x/y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'int' and 'float'
また、_or
オペレーターが float を使用できないという事実は、奇妙です:
>>> x, y = 1., 3.
>>> 0 if (x&y) == 0 and type(x) == type(y) == float else math.log(x/y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'float' and 'float'
>>> x, y = 1., 3.
>>> 0 if (x&y) == 0. and type(x) == type(y) == float else math.log(x/y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'float' and 'float'
>>> x, y = 1, 3
>>> 0 if (x&y) == 0 and type(x) == type(y) == float else math.log(x/y)
-1.0986122886681098
質問は次のとおりです。
- 値ゼロの複数の変数をチェックするPythonicの方法は何ですか?
- また、ブール型のスリップが好きではなく、ゼロを返す代わりにエラーを発生させることが重要です。これを行うにはどうすればよいですか?
- また、x と y を float 型としてチェックするには、どのように解決する必要がありますか?
TypeError: unsupported operand type(s) for |: 'float' and 'float'
(x|y) == 0