gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:15:06 25 4
gpt4 key购买 nike

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

最佳答案

无需导入模块,isinstance()strunicode(3之前的版本——没有unicode in 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'>

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 :

Object type comparisons should always use isinstance() instead of comparing types directly.

关于python - 区分字符串和列表的 Pythonic 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3227552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com