【问题标题】:Python: iterate through two lists and write them to outfile on the same linePython:遍历两个列表并将它们写入同一行的 outfile
【发布时间】:2014-04-18 00:25:00
【问题描述】:

我想同时遍历两个列表,并从两个列表中写入每个项目,在同一行上用制表符分隔。

word = ['run', 'windless', 'marvelous']
pron = ['rVn', 'wIndl@s', 'mArv@l@s']

期望的输出:

run  rVn
windless  wIndl@s
marvelous  mArv@l@s

我尝试使用zip,但它不允许我写入文件:

for w, p in zip(word, pron):
   outfile.write(w, p)

TypeError: function takes exactly 1 argument (2 given)

【问题讨论】:

  • 问题与zip无关。这是文件对象的write 方法采用单个字符串。您正在尝试传递两个字符串。您是否考虑过使用print
  • 打印效果很好,但我真的很想保存到文件中——肯定有办法吗?
  • 在下面查看我的答案。

标签: python list zip


【解决方案1】:

write 只接受一个参数作为参数。要将两个变量写入同一行,请更改:

outfile.write(w, p)

这样它是一个带有制表符和换行符的字符串:

outfile.write("{}\t{}\n".format(w,p))

【讨论】:

  • 嗯,我得到了错误:ValueError: zero length field name in format
  • @user1899415 你必须在 python2.6 上。试试outfile.write("{0}\t{1}\n".format(w,p))
【解决方案2】:

我认为你走在正确的道路上。你只需要给 write() 函数写一行代码。

像这样:

for w, p in zip(word, pron):
    outfile.write("%s, %s" % (w, p))

【讨论】:

  • 这给出了输出:'run', 'windless', 'marvelous', 'rVn', 'wIndl@s', 'mArv@l@s'
  • @user1899415 我不认为您显示的输出与此答案中的代码是可能的...逗号太多,输出应该肯定没有任何单引号。你确定你使用的是这个代码吗?
【解决方案3】:

如果您想让自己的生活更轻松,可以使用 print 语句/函数。

Python 2:

print >>outfile, w, p

Python 3(或 Python 2 在顶部使用 from __future__ import print_function):

print(w, p, file=outfile)

这样您可以避免手动添加 '\n' 或将所有内容转换为单个字符串。

【讨论】:

    猜你喜欢
    • 2016-08-29
    • 2022-11-20
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    相关资源
    最近更新 更多