使用 `map` 将行写入文件

Dhr*_*ati 1 python lambda dictionary function python-2.7

我有一个行列表:

lines = [a,b,c,d]
Run Code Online (Sandbox Code Playgroud)

以及文件列表(通过open(path string,'w')以下方式创建:

files = [e,f,g,h]
Run Code Online (Sandbox Code Playgroud)

我想要做的是将每一行写入其各自的文件(行a应该与文件e和新行一起使用)。请注意,这是一个更大的循环的一部分,用于生成行并将它们放入您看到的此行列表中:

这是我目前的方法:

map(lambda (x,y): y.write(x) + "\n",zip(lines,files))
Run Code Online (Sandbox Code Playgroud)

但这就是我得到的:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Run Code Online (Sandbox Code Playgroud)

什么是实现我需要的方法?将每一行分别写入每个文件非常麻烦。

Neh*_*ani 6

你的意思是:

map(lambda (x,y): y.write(x + "\n"), zip(lines,files))
Run Code Online (Sandbox Code Playgroud)

但我宁愿这样做:

for l, f in zip(lines,files):
    f.write(l + "\n")
Run Code Online (Sandbox Code Playgroud)

  • 强调一下:如果您不打算使用它返回的列表值,请不要使用“map”。 (2认同)