Python:通过字符串列表递归 - 如何区分?
我有以下代码
def printmylist( mylist ):
"""
print tree
"""
try:
for f in mylist:
printmylist( f )
except:
print( " " + mylist )
希望得到类似的输出:
root
branch
leaf
leaf
但由于字符串是可枚举的,所以我得到的
r
o
o
t
.
.
检查类型似乎是unpythonic,那么Pythonian将如何处理这个问题呢?
I have the following code
def printmylist( mylist ):
"""
print tree
"""
try:
for f in mylist:
printmylist( f )
except:
print( " " + mylist )
hoping to get output like:
root
branch
leaf
leaf
but since a string is enumerable, I get
r
o
o
t
.
.
Checking for type seems to be unpythonic, so how would a Pythonian go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,最干净的方法是使用
types.StringTypes
(不要与types.StringType
):或者:
types
模块表明后者是最近版本的 Python 2.x 中的首选方式。The cleanest way that I know of is to use
types.StringTypes
(not to be confused withtypes.StringType
):Alternatively:
Documentation for the
types
module indicates that the latter is the preferred way in recent versions of Python 2.x.我使用以下 pythonic 方法来解决这个问题。不需要
isinstance()
调用。因此它甚至可以与我用 python 封装的各种自定义 C++ 字符串类一起使用。我认为那些基于 isinstance() 的方法在这些情况下不起作用。另外,OP 明确要求一个不涉及类型检查的解决方案。 Pythonistas 检查行为,而不是类型。这里的技巧涉及到字符串有一个不寻常的属性的观察:单字符字符串的第一个元素是相同的单字符字符串。
这适用于 python 2.x:
I use the following pythonic approach to this problem. No
isinstance()
calls required. Therefore it even works with various custom C++ string classes I have wrapped in python. I don't think those isinstance() based methods would work in those cases. Plus the OP explicitly asked for a solution that does not involve type checking. Pythonistas check behavior, not type.The trick here involves the observation that strings have an unusual property: the first element of a one-character string is the same one-character string.
This works in python 2.x:
最简单的是
if type(f) == str
有时使用 if 比使用异常更好。
编辑:
由于拉斯曼的评论,我不推荐这个选项。它在简单使用中很有用,但在专业编码中最好使用
isinstance
。The simplest one is
if type(f) == str
Sometimes it's better to use if's than exceptions.
EDIT:
Due to larsmans comment, I don't recommend this option. It is useful in simple usage, but in professional coding it is better to use
isinstance
.