区分字符串和列表的Pythonic方式是什么?

35 投票
6 回答
9981 浏览
提问于 2025-04-16 01:09

在我的程序中,有很多地方一个对象可能是字符串,也可能是一个包含字符串和其他类似列表的列表。这些对象通常是从一个JSON文件中读取的。它们需要以不同的方式处理。目前,我只是用isinstance这个方法来判断,但我觉得这不是最符合Python风格的做法,所以有没有人能提供一个更好的方法呢?

6 个回答

8

另一种方法是采用“请求原谅总比请求许可好”的做法。在Python中,通常更喜欢使用鸭子类型(duck typing)。你可以先尝试做你想做的事情,比如:

try:
    value = v.split(',')[0]
except AttributeError:  # 'list' objects have no split() method
    value = v[0]
10

因为Python3不再有unicodebasestring这两个东西,所以在这种情况下(你期待的是一个列表或者一个字符串),最好是检查一下是不是list类型。

if isinstance(thing, list):
    # treat as list
else:
    # treat as str/unicode

这样做在Python2和Python3中都是可以用的。

29

你不需要导入任何模块,直接用 isinstance()strunicode(在3之前的版本中有,3里面没有 unicode!)就可以完成你的任务。

Python 2.x:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(u'', (str, unicode))
True
>>> isinstance('', (str, unicode))
True
>>> isinstance([], (str, unicode))
False

>>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):
...     print type(value)
... 
<type 'str'>
<type 'unicode'>
<type 'list'>

Python 3.x:

Python 3.2 (r32:88445, May 29 2011, 08:00:24) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance('☃ ', str)
True
>>> isinstance([], str)
False

>>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):
...     print(type(value))
... 
<class 'str'>
<class 'str'>
<class 'list'>

来自 PEP008 的说明:

比较对象类型时,应该始终使用 isinstance(),而不是直接比较类型。

撰写回答