如何从列表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
答案 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