我试过以下方法:
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
。在
有没有什么方法可以不用循环来检查这一点(即检查列表中的每个元素是否都是元组)?在
可以使用筛选器删除所有元组元素,例如:
然后检查剩余的iterable是否为空。如果在python3.x中,它不是一个列表,但是可以使用
^{pr2}$使用isinstance:
isinstance(object, classinfo)
如果object参数是classinfo参数或其子类(直接、间接或虚拟)的实例,则返回true。
vr is tuple
不检查绑定到名称vr
的对象是否属于tuple
类型,而是检查名称是否绑定到同一对象上(即,评估id(vr) == id(tuple)
)。不可避免地,它们不是;tuple
是type
实例,而不是tuple
实例!在{您应该使用^ a1}:
这支持继承(与例如
if all(type(vr) == tuple ...)
),因此也允许在输入中使用namedtuple
。在但是,在Python中,并不总是需要检查特定对象的类型(它使用强的动态类型,也称为"duck typing")。虽然不清楚为什么要确保它们都是元组,但是,例如,所有都是sequence types(例如
tuple
,list
,str
)是否可以接受?在相关问题 更多 >
编程相关推荐