同时打印多个列表中的所有值
问题内容:
假设我有3个这样的清单
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
如何同时打印出这些列表中的所有内容?做这样的事情的Python方式是什么?
for f in l1,l2 and l3:
print f
这似乎只考虑了两个列表。
所需的输出:对于所有列表中的每个元素,我正在使用不同的功能将它们打印出来
def print_row(filename, status, Binary_Type):
print " %-45s %-15s %25s " % (filename, status, Binary_Type)
然后在for循环中调用上述函数。
问题答案:
我想您可能想要zip
:
for x,y,z in zip(l1,l2,l3):
print x,y,z #1 4 7
#2 5 8
#3 6 9
你在做什么:
for f in l1,l2 and l3:
有点奇怪。它基本上等同于for f in (l1,l3):
sincel2 and l3
返回l3
(假设l2
并且l3
都是非空的-
否则,它将返回空的。)
如果只想连续打印每个列表,则可以执行以下操作:
for lst in (l1,l2,l3): #parenthesis unnecessary, but I like them...
print lst #[ 1, 2, 3 ]
#[ 4, 5, 6 ]
#[ 7, 8, 9 ]