Python3 检查列表是否只包含元组

0 投票
3 回答
534 浏览
提问于 2025-04-18 14:29

我尝试了以下方法:

vrs = [('first text', 1),
       ('second text', 2),
       ('third text', 3),
       ('fourth text', 4),
       ('fifth text', 5),
       ('sixth text', 6),
       ('seventh text', 7),
       ('eighth text', 8),
       ('ninth text', 9),
       ('tenth text', 10),
       ('eleventh text', 11),
       ('twelfth text', 12)
      ]

if all(vr is tuple for vr in vrs):
    print('All are tuples')
else:
    print('Error')

if set(vrs) == {tuple}:
    print('All are tuples')
else:
    print('Error')

但是输出结果都是 Error

有没有什么办法可以检查这个(也就是说,检查列表中的每个元素是否都是元组),而不使用循环呢?

3 个回答

-1

你可以用一个过滤器来去掉所有的元组元素,比如这样:

nontuples = filter(lambda vr : vr is not tuple, vrs)

然后检查剩下的可迭代对象是否为空。如果你使用的是Python 3.x,它不会是一个列表,但你可以用下面的方式把它变成列表:

nontuples = list(nontuples)
2

vr is tuple 这个表达式并不是在检查名字 vr 绑定的对象是否是 tuple 类型,而是在检查 这些名字是否指向同一个对象(也就是说,它在判断 id(vr) == id(tuple))。结果肯定是不一样的;因为 tuple 是一个类型实例,而不是一个 tuple 实例!

所以,你应该使用 isinstance

if all(isinstance(vr, tuple) for vr in vrs):

这样做支持继承(和 if all(type(vr) == tuple ...) 不同),所以这也允许输入像 namedtuple 这样的类型。

不过,在 Python 中,并不总是需要检查特定对象的类型(它使用的是强类型和动态类型,也叫做 “鸭子类型”)。虽然不太清楚你为什么想确保它们都是元组,但是否有可能,比如说,所有的输入都是 序列类型(比如 tupleliststr)也是可以接受的呢?

4

使用 isinstance 函数:

isinstance(object, classinfo)

如果第一个参数的对象是第二个参数所代表的类的实例,或者是这个类的子类(直接的、间接的或虚拟的),那么就返回真(True)。

vrs = [('first text', 1),
   ('second text', 2),
   ('third text', 3),
   ('fourth text', 4),
   ('fifth text', 5),
   ('sixth text', 6),
   ('seventh text', 7),
   ('eighth text', 8),
   ('ninth text', 9),
   ('tenth text', 10),
   ('eleventh text', 11),
   ('twelfth text', 12)
  ]    
all(isinstance(x,tuple) for x in vrs)
True
vrs = [('first text', 1),
   ('second text', 2),
   ('third text', 3),
   ('fourth text', 4),
   ('fifth text', 5),
   ('sixth text', 6),
   ('seventh text', 7),
   ('eighth text', 8),
   ('ninth text', 9),
   ('tenth text', 10),
   ('eleventh text', 11),
   'twelfth text'
  ]
  all(isinstance(x,tuple) for x in vrs)
  False

撰写回答