2012-07-30 103 views
1

我可以以某种方式查看元组内容的类型和大小吗?我想输出是这样的:元组类型内容python

(str, list, int)或什么是可能的(只是打印它们是很难,因为有嵌套表)

x = someSecretTupleFromSomewhereElse 
print type(x) 

<(type 'tuple')> 

回答

9
>>> data = ('ab', [1, 2, 3], 101) 
>>> map(type, data) 
[<type 'str'>, <type 'list'>, <type 'int'>] 

还显示,你可以做到这一点的长度,对于不是序列的项目,我只会显示None

>>> import collections 
>>> [(type(el), len(el) if isinstance(el, collections.Sequence) else None) 
    for el in data] 
[(<type 'str'>, 2), (<type 'list'>, 3), (<type 'int'>, None)] 
+2

不知道你可以映射到元组,cool:D – 2012-07-30 06:53:45

+2

@Vixen:'map()'适用于任何序列。 – 2012-07-30 06:54:55

+0

@ IgnacioVazquez-Abrams你的意思是任何迭代? – jamylak 2012-07-30 07:31:12