如何检查对象是列表还是元组(而不是字符串)? [英] How to check if an object is a list or tuple (but not string)?

查看:73
本文介绍了如何检查对象是列表还是元组(而不是字符串)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我通常要执行的操作,以确定输入是list/tuple-而不是str.因为很多时候我偶然发现了一个错误,即一个函数错误地传递了一个str对象,而目标函数却假定lst实际上是一个listtuple来执行for x in lst.

This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target function does for x in lst assuming that lst is actually a list or tuple.

assert isinstance(lst, (list, tuple))

我的问题是:有没有更好的方法来实现这一目标?

My question is: is there a better way of achieving this?

推荐答案

仅在python 2中(不是python 3):

In python 2 only (not python 3):

assert not isinstance(lst, basestring)

实际上就是您想要的,否则您会错过很多像列表一样的东西,但它们不是listtuple的子类.

Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of list or tuple.

这篇关于如何检查对象是列表还是元组(而不是字符串)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆