代码之家  ›  专栏  ›  技术社区  ›  mins

可以用列表理解来解包元组列表吗?

  •  2
  • mins  · 技术社区  · 7 年前

    我想使用列表理解将元组列表中的元组解压为单个变量。E、 g.如何使用列表理解而不是显式循环进行第二次打印:

    tuples = [(2, 4), (3, 9), (4, 16)]
    
    # Print in direct order OK
    print(('Squares:' + '   {} --> {}' * len(tuples)).format(
        *[v for t in tuples for v in t]))
    
    # Print in reverse order not possible
    print('Square roots:', end='')
    for t in tuples:
        print ('   {} --> {}'.format(t[1], t[0]), end='')
    print()
    
    >>> Squares:   2 --> 4   3 --> 9   4 --> 16
    >>> Square roots:   4 --> 2   9 --> 3   16 --> 4
    

    是否可以用列表理解替换第二个打印循环? 如果合适,可以进一步简化。

    1 回复  |  直到 7 年前
        1
  •  1
  •   willeM_ Van Onsem    7 年前

    在里面 print 是一个函数,因此您确实可以编写:

    [print ('   {} --> {}'.format(*t[::-1]), end='') for t in tuples]
    

    但这可能比使用 for 循环,因为现在您为每个迭代分配内存。如果迭代次数很大,您将构建一个巨大的列表,其中包含 None s

    它产生:

    >>> tuples = [(2, 4), (3, 9), (4, 16)]
    >>> [print ('   {} --> {}'.format(*t[::-1]), end='') for t in tuples]
       4 --> 2   9 --> 3   16 --> 4[None, None, None]
    

    这个 [None, None, None] 不是打印出来的,只是列表理解的结果。

    但也就是说,我们不需要列表理解,我们可以使用 ''.join(..)

    print('Squares:'+''.join('   {} --> {}'.format(*t) for t in tuples))
    print('Square roots:'+''.join('   {} --> {}'.format(*t[::-1]) for t in tuples))
    

    这将产生:

    >>> print('Squares:'+''.join('   {} --> {}'.format(*t) for t in tuples))
    Squares:   2 --> 4   3 --> 9   4 --> 16
    >>> print('Square roots:'+''.join('   {} --> {}'.format(*t[::-1]) for t in tuples))
    Square roots:   4 --> 2   9 --> 3   16 --> 4