I have list of tuples
sortedlist = [('hello', 41), ('hi', 16), ('bye', 4)]
which I want to write to a .txt file so that the word and integer from each tuple are on the same line separated by a tab. i.e.
hello 41
hi 16
bye 4
I know how to write to the file i.e.
with open("output/test.txt", "w") as out_file:
for item in sorted list:
out_file.write("Hello, world!" "\n")
but I'm struggling to figure out how to create a loop though my list that will give me the correct output.
I've tried:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.write((str(sortedlist[i](0))) str(sortedlist[i](1)))
but I get:
TypeError: list indices must be integers or slices, not tuple
what should I be doing instead?
CodePudding user response:
The i
in your loop is actually the values in the list, e.g. ('hello', 41)
(Try print(i)
inside the loop to see).
This means you're actually doing sortedlist[('hello', 41)]
inside the loop - trying to use the tuple
as an index into your list
, which explains the exception you're getting.
You can use this to access the items in i
in your loop:
with open("output/test.txt", "w") as out_file:
for i in sortedlist:
out_file.write((str(i[0])) str(i[1]))
If you wanted i
to be the indices into the list, you can use for i in range(len(sortedlist)):
, but you shouldn't do this if you are just accessing the members of the list in order.
Finally, you can use sequence unpacking to make the solution even neater:
with open("output/test.txt", "w") as out_file:
for a, b in sortedlist:
out_file.write(f"{a}\t{b}\n")
You should ideally give a
and b
appropriate names. I've also modified this to insert the tab and newline characters from your example, and using a f-string to format it as a string.
CodePudding user response:
You have written incorrect code that's why you are getting an error. Here i in for loop is not the index but the element of the list you are iterating through. So, to iterate through the index you need to use range(len(sortedlist)). To get your favourable output, you should modify your code as:
with open("test.txt", "w") as out_file:
for i in range(len(sortedlist)):
out_file.write((str(sortedlist[i][0])) '\t' str(sortedlist[i][1]) '\n')
In this way your output will be:
hello 41
hi 16
bye 4