【问题标题】:Tuple type content python元组类型内容python
【发布时间】:2012-07-30 06:50:18
【问题描述】:

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

(str, list, int) 或任何可能的方式(仅打印它们很困难,因为存在嵌套列表)

x = someSecretTupleFromSomewhereElse
print type(x)

<(type 'tuple')>

【问题讨论】:

    标签: python types tuples instanceof


    【解决方案1】:
    >>> 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)]
    

    【讨论】:

    • @IgnacioVazquez-Abrams 你的意思是任何可迭代的吗?
    • 按尺寸长度,抱歉造成混淆
    • @Vixen 好的,我可以更改我的答案,但是如果对象没有长度(例如int),您希望显示什么?
    • 它永远不会发生,所以不用担心:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多