【问题标题】:Write to file from list of tuples with strings and integers从带有字符串和整数的元组列表写入文件
【发布时间】:2022-01-10 20:41:16
【问题描述】:

我有元组列表

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

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

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")

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

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

我应该怎么做?

【问题讨论】:

    标签: python list tuples txt


    【解决方案1】:

    循环中的 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)):,但如果您只是按顺序访问列表中的成员,则不应这样做。另见enumerate

    最后,您可以使用sequence unpacking 使解决方案更加整洁:

    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 将其格式化为字符串。

    【讨论】:

      【解决方案2】:

      您编写了不正确的代码,这就是您收到错误的原因。这里 i in for 循环不是索引,而是您正在迭代的列表的元素。因此,要遍历索引,您需要使用 range(len(sortedlist))。 为了获得您满意的输出,您应该将您的代码修改为:

      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')
      

      这样你的输出将是:

      hello   41
      hi  16
      bye 4
      

      【讨论】:

        【解决方案3】:
        
        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() 函数中的 [i]。 以下是适合您的代码:

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

        writeline() 函数自动在字符串末尾追加一个换行符。

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

        map 函数将第二个参数的每个元素映射到作为第一个参数提供的函数中。然后将该函数的输出附加到一个可迭代对象,从而产生新的元素可迭代对象,这些元素是第二个 arg 元素的函数。

        map(func, iterable)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-05
          • 1970-01-01
          • 1970-01-01
          • 2020-04-17
          • 1970-01-01
          • 1970-01-01
          • 2021-10-27
          • 1970-01-01
          相关资源
          最近更新 更多