【问题标题】:What is the Pythonic Way of Differentiating Between a String and a List?区分字符串和列表的 Pythonic 方式是什么?
【发布时间】:2010-07-12 10:11:57
【问题描述】:

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

【问题讨论】:

标签: python json typechecking


【解决方案1】:

无需导入模块,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(),而不是直接比较类型。

【讨论】:

  • 现在应该劝阻人们不要使用 basestring,因为它在 Python 3 中不存在。
  • 您可以在 Python 3 中使用basestring = str 模拟这种行为。但我想就是这样。
  • isinstance 的第二个参数可以是一个元组,所以这比检查basestring 更好:isinstance(u'', (str, unicode))
  • 这是最短的答案:stackoverflow.com/a/26797688/99834 两者都适用。
【解决方案2】:

由于 Python3 不再有 unicodebasestring,在这种情况下(您期望的是列表或字符串)最好针对 list 进行测试

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

因为它同时兼容 Python2 和 Python3

【讨论】:

  • 如果thingtupledictset 等呢?
  • @Johnsyweb,如果有其他类型的可能性,那么答案会有所不同。这个问题说它是一个列表或一个字符串
  • 亲爱的投票者,请考虑发表评论,以便我改进我的答案
  • 通常,对象是单个项目或某些项目容器。通常最好测试isinstance(object, item_type),这样代码就不会局限于单一的容器类型。
【解决方案3】:

另一种方法,使用“请求原谅比请求许可更好”的做法,在 Python 中通常首选鸭式输入,您可以先尝试做您想做的事情,例如:

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

【讨论】:

  • isinstance 的答案不同,这种方法能够更好地泛化以区分自定义字符串类型和其他自定义序列类型。
【解决方案4】:

使用isinstance

在 Python>=2.3 上,字符串可能是 strunicode 类型。检查两种情况:

if isinstance(a,basestring): # same as isinstance(obj, (str, unicode))
   print "Object is a string"

从 Python 3 开始,只存在一种字符串类型,因此您应该使用 str 而不是 basestring

if isinstance(a,str):
   print "Object is a string"

【讨论】:

    【解决方案5】:

    因为我喜欢保持简单,这里是与 2.x 和 3.x 兼容的最短形式:

    # trick for py2/3 compatibility
    if 'basestring' not in globals():
       basestring = str
    
    v = "xx"
    
    if isinstance(v, basestring):
       print("is string")
    

    【讨论】:

      【解决方案6】:

      您可以使用类型模块:

      import types
      if type(ls) == types.ListType:
          #your code for list objects here
      

      【讨论】:

      • 比较类型的首选方法是使用isinstanceis 运算符。 docs.python.org/library/types.html
      • 您可以使用type(ls) is list,但这不适用于列表的子类
      • @Lars Wirzenius:不。这会尝试调用某种比较,而 type 类型对象的默认比较是比较对象 ID,这导致与 @ 相同的行为987654327@,不保证。在这种情况下,is 或者最好是isinstance 是正确答案。
      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 2021-10-16
      • 2012-08-02
      • 1970-01-01
      • 2012-04-16
      • 2021-07-03
      • 2010-11-18
      • 1970-01-01
      相关资源
      最近更新 更多