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

2024-05-05 23:39:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过以下方法:

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。在

有没有什么方法可以不用循环来检查这一点(即检查列表中的每个元素是否都是元组)?在


Tags: 方法textiferrorallelsearefirst
3条回答

可以使用筛选器删除所有元组元素,例如:

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

然后检查剩余的iterable是否为空。如果在python3.x中,它不是一个列表,但是可以使用

^{pr2}$

使用isinstance

isinstance(object, classinfo)

如果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

vr is tuple不检查绑定到名称vr的对象是否属于tuple类型,而是检查名称是否绑定到同一对象上(即,评估id(vr) == id(tuple))。不可避免地,它们不是;tupletype实例,而不是tuple实例!在

{您应该使用^ a1}:

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

这支持继承(与例如if all(type(vr) == tuple ...)),因此也允许在输入中使用namedtuple。在

但是,在Python中,并不总是需要检查特定对象的类型(它使用强的动态类型,也称为"duck typing")。虽然不清楚为什么要确保它们都是元组,但是,例如,所有都是sequence types(例如tupleliststr)是否可以接受?在

相关问题 更多 >