问题
Is there a substantial difference in Python 3.x between:
for each_line in data_file:
if each_line.find(":") != -1:
#placeholder for code
#more placeholder
and
for each_line in data:
if not each_line.find(":") == -1:
#placeholder for code
#more placeholder
My question isn't particular to the above usage, but is more general or essential - is this syntactical difference working in a different way, even though the result is the same? Is there a logical difference? Are there tasks where one is more appropriate or is this solely a stylistic difference? If this is merely stylistic, which one is considered cleaner by Python programmers?
Also, is the above an opposite instance of asking what the difference is between is
and ==
? Is the former, like the latter, a difference of object identity and object value equality? What I mean is, in my above example, is the is
in using not
implicit?
回答1:
As I understand it,
functionally they are not entirely the same; if you are comparing against a class, the class could have a member function, __ne__
which is called when using the comparison operator !=, as opposed to __eq__
which is called when using the comparison ==
So, in this instance,not (a == b)
would call __eq__
on a, with b as the argument, then not
the result(a != b)
would call __ne__
on a, with b as the argument.
I would use the first method (using !=) for comparison
回答2:
Different rich comparison methods are called depending on whether you use ==
or !=
.
class EqTest(object):
def __eq__(self, other):
print "eq"
return True
def __ne__(self, other):
print "ne"
return False
a = EqTest()
b = EqTest()
print not (a == b)
# eq
# False
print a != b
# ne
# False
As far as I know, you will get the same result for all built-in types, but theoretically they could have different implementations for some user-defined objects.
I would use !=
instead of not
and ==
simply because it is one operation instead of two.
回答3:
Your first example is how you should be testing the result of find
.
Your second example is doing too much. It is additionally performing a boolean not on the result of the each_line.find(":") == -1
expression.
In this context, where you want to use not
is when you have something that you can test for truthiness or falsiness.
For example, the empty string ''
evaluates to False:
s = ''
if not s:
print('s is the empty string')
You seem to be conflating a little bit the identity-test expressions is
and is not
with the boolean not
.
An example of how you'd perform an identity test:
result_of_comparison = each_line.find(":") == -1
if result_of_comparison is False: # alternatively: is not True
pass
来源:https://stackoverflow.com/questions/9798407/is-there-a-logical-difference-between-not-and-without-is