Issue
Say I have two lists:
a = [1, 2, 3, 4]
b = [hello, how, iz, life]
How can I make a new list c
that takes each element in list a
and matches it in order to an element in list b
? I want the text file to look something like this:
1 hello
2 how
3 iz
4 life
I attempted c.append(a,b)
, but I got the following error:
TypeError: list.append() takes exactly one argument (2 given)
Solution
Try the following:
a = [1, 2, 3, 4]
b = ["hello", "how", "iz", "life"]
c = zip(a,b)
with open("sample.txt", 'w') as outfile:
for elem in c:
outfile.write(str(elem[0]) + " " + elem[1] +"\n")
This will output:
1 hello
2 how
3 iz
4 life
to a file called sample.txt.
Edit:
Kelly makes a great point you can just simplify the line as print(*elem, file=outfile)
. I looked at the docs for print and I was surprised to find that the print function defines a separator for elements given in the *objects argument and ends the line with a newline through default arguments, which provides us with the same desired output.
Answered By - Richard K Yu Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.