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

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

问题描述

为了确定输入是 list/tuple 而不是 str,我通常会这样做.因为很多时候我偶然发现了一个错误,其中一个函数错误地传递了一个 str 对象,并且目标函数执行 for x in lst 假设 lst实际上是一个 listtuple.

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天全站免登陆