【问题标题】:Iterate in a list that contain tuples and int in Python在 Python 中迭代包含元组和 int 的列表
【发布时间】:2019-05-04 06:19:49
【问题描述】:

所以我创建了这个列表:

l = [(1,2,3),(4,5),6]

但是当我这样做时:

for i in l:
    print (i[0])

它向我发送此错误消息:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: object of type 'int' has no len()

所以我想知道如果它是int 或第一个元素如果它是tuple,是否有打印数字的方法...

希望我已经为你说清楚了,如果你不明白,请不要犹豫。

提前谢谢你。

【问题讨论】:

    标签: python list loops tuples


    【解决方案1】:

    使用isinstance:

    l = [(1,2,3),(4,5),6]
    for i in l:
        if isinstance(i,int):
            print(i)
        elif isinstance(i,tuple):
            print(i[0])
    # 1
    # 4
    # 6
    

    使用列表推导,以列表形式输出:

    [i if isinstance(i,int) else i[0] for i in l]
    # [1, 4, 6]
    

    【讨论】:

    • 是的,只是打印(i if isinstance(i, int) else i[0])
    • @OlivierMelançon 简而言之,您能告诉我使用isinstance 与直接比较相比的优势吗?
    • @meW 本身并不是“更好”,但它考虑了继承,并且在某些特定情况下更加通用。
    【解决方案2】:

    为了支持其他数据类型(浮点数而不是整数,列表而不是元组):

    for i in l:
        try:
            print(i[0])
        except TypeError:
            print(i)
    

    请注意,如果您想打印字符串的所有字符,这将不起作用。

    【讨论】:

    • “请求宽恕比请求许可更容易”(try...except)通常比if...else更Pythonic。
    • 虽然超出了问题的范围,但需要注意的是,如果i 的类型为str,则会打印i 的第一个字符,而不是所有i .例如i == '90' 会给9 而不是90
    【解决方案3】:

    好吧,如果您想安全并打印可迭代的第一项,您可以应用下标,hasattr 检查 Python 对象是否具有某种方法,其中__getitem__ 相当于切片函数:

    l = [(1,2,3),[4,5],6]
    
    for i in l:
        if hasattr(i, '__getitem__'):
            print(i[0])
        else:
            print(i)
    
    >> 1
    4
    6
    

    这确保您始终可以从序列中选择一个索引,给定类型listtuples。请注意,str 类型也是可迭代的序列。如果你想排除它们,你可以使用isinstance来检查对象的类型,在这个例子中我们检查not stris Iterable

    import collections
    
    for i in l:
        if not isinstance(i, str) and isinstance(i, collections.Iterable):
            print(i[0])
        else:
            print(i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      相关资源
      最近更新 更多