这两个代码片段之间有什么区别?使用type():
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
使用isinstance():
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
Run Code Online (Sandbox Code Playgroud) 在python中有一个简单的方法来判断某些东西是不是一个序列?我试着这么做:
if x is not sequence但是python并不喜欢这样
我读了这个问题
但是当使用下面的代码时,我会得到一个假的np.array,如下所示.
import collections
isinstance(np.arange(10), collections.Sequence)
# returns false
Run Code Online (Sandbox Code Playgroud)
我觉得有点烦人,我不能做len(1),只是得到1.
我能想到的唯一工作是try except如下声明:
a = 1
try:
print len(a)
except TypeError:
print 1
Run Code Online (Sandbox Code Playgroud)
是否有更多的Pythonic方法来做到这一点?
python ×3
if-statement ×1
inheritance ×1
iterable ×1
oop ×1
sequence ×1
sequences ×1
typechecking ×1
types ×1