简体   繁体   English

从带有字符串和整数的元组列表写入文件

[英]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.我想将其写入 a.txt 文件,以便每个元组中的单词和 integer 位于由制表符分隔的同一行上。 ie 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.但我正在努力弄清楚如何通过我的列表创建一个循环,该列表将为我提供正确的 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).循环中的i实际上是列表中的值,例如('hello', 41) (尝试在循环中使用print(i)来查看)。

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.这意味着您实际上是在循环内执行sortedlist[('hello', 41)] - 尝试将tuple用作list的索引,这解释了您遇到的异常。

You can use this to access the items in i in your loop:您可以使用它来访问循环中i中的项目:

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.如果您希望i成为列表中的索引,您可以使用for i in range(len(sortedlist)): ,但如果您只是按顺序访问列表的成员,则不应这样做。

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.理想情况下,您应该给ab适当的名称。 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.我还对其进行了修改,以插入示例中的制表符和换行符,并使用f-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.这里 i in for 循环不是索引,而是您正在迭代的列表的元素。 So, to iterate through the index you need to use range(len(sortedlist)).因此,要遍历索引,您需要使用 range(len(sortedlist))。 To get your favourable output, you should modify your code as:要获得您喜欢的 output,您应该将代码修改为:

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:这样,您的 output 将是:

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在上面的代码中,您使用 'i' 作为 'sortedlist' 的索引,但这里的 'i' 用于迭代元组,因此

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.要修复它,您可以遍历 forloop 中的范围或删除.write() function 中的 [i]。 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. writeline() function 自动在字符串末尾附加一个换行符。

' '.join(iterable) will join the iterable elements using a delimiter specified in the string before it. ' '.join(iterable) 将使用在它之前的字符串中指定的分隔符连接可迭代元素。 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. map function 将第二个参数的每个元素映射到作为第一个参数提供的 function 中。 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. 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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