简体   繁体   中英

Write to file from list of tuples with strings and integers

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. ie

hello    41 
hi    16 
bye    4 

I know how to write to the file ie

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?

The i in your loop is actually the values in the list, eg ('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.

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

with open("output/test.txt", "w") as out_file:
        for i in sortedlist: 
            out_file.write((str(sortedlist[i](0))) + str(sortedlist[i](1)))

In the above code you are using 'i' as index for 'sortedlist' but 'i' here is used to iterate over the tuples thus

sortedlist[i]  implies  sortedlist[("hello", 41)] which gives you the error!

To fix it you can either iterate over a range in the forloop or remove the [i] in the.write() function. Below is the code that should work for you:

with open("output/test.txt", "w") as out_file:
    for i in sortedlist:
        out_file.writeline(' '.join(map(str, i)))

The writeline() function automatically appends a newline at the end of the string.

' '.join(iterable) will join the iterable elements using a delimiter specified in the string before it. I didnt specify one thus it uses space.

The map function maps every single element of the second argument into the function provided as first argument. Then the output of that function is append to an iterable thus producing new iterable of elements which are a function of the elements of second arg.

map(func, iterable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM