问题
I have a question about python.
I have variables a
, b
, c
and d
.
And I have the following line:
if not isinstance(a, int) or not isinstance(b, int) \
or not isinstance(c, int) or not isinstance(d, int) \
or not isinstance(a, float) or not isinstance(b, float)\
or not isinstance(c, float) or not isinstance(d, float):
do something
Is it possible to make this code shorter?
Thanks!
回答1:
U should use all
:
if not all(isinstance(var, (int, float)) for var in [a, b, c, d]):
# do stuff
Note, that you can supply both int
and 'float' to the isinstance
call.
回答2:
Try the following:
>>> a = 1
>>> b = 1.0
>>> c = 123
>>> d = 233
>>> any((type(var) in (int, float) for var in [a,b,c,d]))
True
>>> c = 'hello'
>>> any((type(var) in (int, float) for var in [a,b,c,d]))
True
>>>
回答3:
>>> a = b = c = d = []
>>> any(not isinstance(x, (int, float)) for x in [a,b,c,d])
True
>>> d = 0
>>> any(not isinstance(x, (int, float)) for x in [a,b,c,d])
False
回答4:
Actually, what you've write is equal to
if True:
do_somthing
pass
回答5:
Clearly, you didn't take enough attention to the RemcoGerlich's comment, since you upvoted and accepted a senseless answer.
At the time I write this, 4 other people upvoted the same senseless answer.
That's incredible.
Will you see better with this ? :
def OP(a,b,c):
return not isinstance(a, int)\
or not isinstance(b, int)\
or not isinstance(c, int)\
or not isinstance(a, float)\
or not isinstance(b, float)\
or not isinstance(c, float)
def AZ(a,b,c):
return all(isinstance(var, (int, float))
for var in [a, b, c])
gen = ((a,b,c) for a in (1, 1.1 ,'a')
for b in (2, 2.2, 'b') for c in (3, 3.3, 'c'))
print ' OPv | AZv OPv is AZv\n'\
' -----|----- -----------'
OPV_list = []
for a,b,c in gen:
OPv = OP(a,b,c)
OPV_list.append(OPv)
AZv = AZ(a,b,c)
print '%3r %3r %3r %s | %s %s'\
% (a,b,c,OPv,AZv,OPv is AZv if OPv is not AZv else '')
print '------------- ----'
print 'all(OPV_list) : ',all(OPV_list)
result
OPv = yours
AZv = senseless answer
I limited to a,b,c to make it short
OPv | AZv OPv is AZv
-----|----- -----------
1 2 3 True | True
1 2 3.3 True | True
1 2 'c' True | False False
1 2.2 3 True | True
1 2.2 3.3 True | True
1 2.2 'c' True | False False
1 'b' 3 True | False False
1 'b' 3.3 True | False False
1 'b' 'c' True | False False
1.1 2 3 True | True
1.1 2 3.3 True | True
1.1 2 'c' True | False False
1.1 2.2 3 True | True
1.1 2.2 3.3 True | True
1.1 2.2 'c' True | False False
1.1 'b' 3 True | False False
1.1 'b' 3.3 True | False False
1.1 'b' 'c' True | False False
'a' 2 3 True | False False
'a' 2 3.3 True | False False
'a' 2 'c' True | False False
'a' 2.2 3 True | False False
'a' 2.2 3.3 True | False False
'a' 2.2 'c' True | False False
'a' 'b' 3 True | False False
'a' 'b' 3.3 True | False False
'a' 'b' 'c' True | False False
------------- ----
all(OPV_list) : True
来源:https://stackoverflow.com/questions/20704455/python-checking-type-of-variables