I'm writing this function that checks if a list of lists would be a valid sudoku puzzle. When I'm checking the lists for valid integers I'm getting unexpected results.
For example:
lst = [[1,2,3],[2,3,1],[4,2,1]]
for i in lst:
for v in i:
print type(v)
<type 'int'> #all the way through
for i in lst:
for v in i:
if v is int:
print True
Prints nothing, and when I through in:
for i in lst:
for v in i:
if v is not int:
print False
Prints all False? Not sure about what is going on, especially with the type showing they're integers.
Instead of saying
if v is int:
Which is asking if v is the actual type int
Say
if isinstance(v, int):
which says v is an instantiated int
(or subclass)
Here is an example, first with an integer (or instantiated int
)
>>> v = 17
>>> type(v)
<type 'int'>
>>> v is int
False
>>> isinstance(v, int)
True
>>>
Next with a type
>>> v = int
>>> type(v)
<type 'type'>
>>> v is int
True
>>> isinstance(v, int)
False
>>>
No integer is the same object as int
. You want to use isintance
.
You don't want to use type(v) == int
, because that will evaluate to False if v
is a subclass of int
, which is in most cases not the desired behaviour at all; if you do really, really want that, do type(v) is int
, because is
is the expected style for comparison with a specific object (which is what a type is).
v is not int
is the same as saying, but a more readable version of
not v is int
is
compares the references of each operand (not the types) to see if they are the same. Here is an example of that:
>>> x = (1,2,3)
>>> y = (1,2,3)
>>> x == y
True
>>> x is y
False
So v is int
obviously evaluates to False
. not
turns False
into True
and the if statement prints.
Use isinstance(v, int)
for the correct result.
回答您应该使用isinstance的答案是正确的,但是另一种替代方法是使用if type(v) == int
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.