Python 3.x 可以用列表解压元组列表吗?
我想使用列表理解将元组列表中的元组解压为单个变量。例如,如何使用列表理解而不是显式循环进行第二次打印:Python 3.x 可以用列表解压元组列表吗?,python-3.x,list-comprehension,Python 3.x,List Comprehension,我想使用列表理解将元组列表中的元组解压为单个变量。例如,如何使用列表理解而不是显式循环进行第二次打印: 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 possib
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
是否可以用列表替换第二个打印循环?
如果合适的话,可以进一步简化。中的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]
>>> 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
[None,None,None]
不打印,只是列表理解的结果
但是也就是说,我们不需要理解列表,我们可以使用'.join(..)
(使用列表或生成器),如:
print('Squares:'+''.join(' {} --> {}'.format(*t) for t in tuples))
print('Square roots:'+''.join(' {} --> {}'.format(*t[::-1]) for t in tuples))
这将产生:
>>> 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]
>>> 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
我缺少的是
t[::-1]
:-)现在我也看到了生成器的好处。