繁体   English   中英

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

[英]Write to file from list of tuples with strings and integers

我有元组列表

sortedlist = [('hello', 41), ('hi', 16), ('bye', 4)]

我想将其写入 a.txt 文件,以便每个元组中的单词和 integer 位于由制表符分隔的同一行上。 IE

hello    41 
hi    16 
bye    4 

我知道如何写入文件,即

with open("output/test.txt", "w") as out_file:
        for item in sorted list: 
            out_file.write("Hello, world!" + "\n")

但我正在努力弄清楚如何通过我的列表创建一个循环,该列表将为我提供正确的 output。
我试过了:

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

但我得到:

TypeError: list indices must be integers or slices, not tuple

我应该怎么做呢?

循环中的i实际上是列表中的值,例如('hello', 41) (尝试在循环中使用print(i)来查看)。

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

您可以使用它来访问循环中i中的项目:

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

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

最后,您可以使用序列解包来使解决方案更加整洁:

with open("output/test.txt", "w") as out_file:
  for a, b in sortedlist: 
    out_file.write(f"{a}\t{b}\n")

理想情况下,您应该给ab适当的名称。 我还对其进行了修改,以插入示例中的制表符和换行符,并使用f-string将其格式化为字符串。

您编写了不正确的代码,这就是您收到错误的原因。 这里 i in for 循环不是索引,而是您正在迭代的列表的元素。 因此,要遍历索引,您需要使用 range(len(sortedlist))。 要获得您喜欢的 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')

这样,您的 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)))

在上面的代码中,您使用 'i' 作为 'sortedlist' 的索引,但这里的 'i' 用于迭代元组,因此

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

要修复它,您可以遍历 forloop 中的范围或删除.write() function 中的 [i]。 以下是应该为您工作的代码:

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

writeline() function 自动在字符串末尾附加一个换行符。

' '.join(iterable) 将使用在它之前的字符串中指定的分隔符连接可迭代元素。 我没有指定一个,因此它使用空间。

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.

map(func, iterable)

暂无
暂无

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

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