在python中输出列表

时间:2013-11-12 15:13:32

标签: python list python-3.x

如何从列表A和B生成outfile.txt:

A = ['x','y','z']
B = [[1,2,3],[4,5,6],[7,8,9]]

我的不完整代码是:

with open ('outfile.txt','w') as outfile:
    for a, b in zip (A,B):
        print (a, b, file=outfile)

outfile.txt应如下所示:

x 1 2 3
y 4 5 6
z 7 8 9

1 个答案:

答案 0 :(得分:5)

使用b splat语法传入*列表,将值展开为单独的参数:

with open ('outfile.txt','w') as outfile:
    for a, b in zip (A, B):
        print (a, *b, file=outfile)

演示:

>>> import sys
>>> A = ['x','y','z']
>>> B = [[1,2,3],[4,5,6],[7,8,9]]
>>> for a, b in zip (A, B):
...     print (a, *b, file=sys.stdout)
... 
x 1 2 3
y 4 5 6
z 7 8 9