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

Nik*_*win 27 python

对于我的程序,我有很多地方,对象可以是字符串或包含字符串和其他类似列表的列表.这些通常是从JSON文件中读取的.他们都需要区别对待.现在,我只是使用isinstance,但这并不是最狡猾的方式,所以有没有人有更好的方法呢?

Joh*_*web 27

不需要输入模块isinstance(), strunicode(3之前的版本-没有unicode!3)会为你做这项工作.

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'>
Run Code Online (Sandbox Code Playgroud)

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'>
Run Code Online (Sandbox Code Playgroud)

来自PEP008:

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

  • 你可以使用`basestring = str`在Python 3中模拟这种行为.但我认为这就是它. (2认同)

Joh*_*ooy 9

由于Python3不再具有unicode或者basestring,在这种情况下(你期望列表或字符串),最好测试list

if isinstance(thing, list):
    # treat as list
else:
    # treat as str/unicode
Run Code Online (Sandbox Code Playgroud)

因为它兼容Python2和Python3

  • 如果`thing` 是`tuple`、`dict` 或`set` 等,那又如何呢? (2认同)
  • @Johnsyweb,如果有其他类型的可能性,那么答案会有所不同.这个问题说它是列表或字符串 (2认同)
  • 亲爱的downvoter,请考虑发表评论,以便我可以改进我的答案 (2认同)

kni*_*kum 5

另一种方法,使用“请求宽恕比许可更好”的做法,在 Python 中通常首选鸭子类型,您可以尝试先做您想做的事,例如:

try:
    value = v.split(',')[0]
except AttributeError:  # 'list' objects have no split() method
    value = v[0]
Run Code Online (Sandbox Code Playgroud)