Python: iterate through two lists and write them t

2020-04-27 09:20发布

I would like to iterate through two lists simultaneously and write each item from both lists, tab-separated on the same line.

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

Desired output:

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

I tried using zip but it doesn't let me write to file:

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

TypeError: function takes exactly 1 argument (2 given)

标签: python list zip
3条回答
Viruses.
2楼-- · 2020-04-27 09:50

write only takes one argument as a parameter. To write both variables in the same line, change:

outfile.write(w, p)

such that it is one string with a tab and a newline:

outfile.write("{}\t{}\n".format(w,p))
查看更多
Rolldiameter
3楼-- · 2020-04-27 10:05

If you want to make life easier for yourself you can use the print statement/function.

Python 2:

print >>outfile, w, p

Python 3 (or Python 2 using from __future__ import print_function at the top):

print(w, p, file=outfile)

This way you can avoid manually adding the '\n' or converting everything to a single string.

查看更多
对你真心纯属浪费
4楼-- · 2020-04-27 10:12

I think you're on the right path. You just need to give the write() function a single line to write.

Like this:

for w, p in zip(word, pron):
    outfile.write("%s, %s" % (w, p))
查看更多
登录 后发表回答