将嵌套列表写入.txt文件

时间:2017-11-05 21:17:15

标签: python

给定列表列表,其中每个内部列表由字符串和浮点数组成,以及用于写入的打开文件,将每个内部列表的内容写为文件中的一行。文件的每一行应该是字符串,后面跟逗号分隔的浮点数。完成后关闭文件。

def write_avg(L, out_file):  
    '''(list, file) -> NoneType
    >>> L = [['a', 2.0], ['b', 3.0], ['c', 4.0]]  
    a, 2.0  
    b, 3.0  
    c, 4.0  
    '''
    L1 = []  
    L2 = []  
    myList = []    
    for item in L:  
        if item == str:  
            item.append(L1)  
        elif item == float:  
            item.append(L2)  
        else:  
            return "error"  
        myList.append(L1, L2)  
    out_file.writelines(myList)  

如何为.txt文档的每一个新行添加一个列表?

4 个答案:

答案 0 :(得分:2)

如果您正在使用Python和表格,我推荐使用pandas库。 输出可以在一行中实现,如下所示:

GDP

答案 1 :(得分:1)

您可以使用列表:

from tabulate import tabulate

with open(file, "a") as writedfile:
    writedfile.write(tabulate(list, headers=headers))

答案 2 :(得分:0)

使用python列表表达式可以执行以下操作:

myList = ["{0}, {1}".format(x1, x2) for (x1, x2) in L]
with open('filename.txt', 'w') as out_file:
    out_file.writelines(myList)

这将为

创建
L = [['a', 2.0], ['b', 3.0], ['c', 4.0]]  

此输出:

  

a,2.0
  b,3.0
  c,4.0

答案 3 :(得分:0)

试试这个:

lst = [['a', 2.0], ['b', 3.0], ['c', 4.0]]

filename = 'test.txt'

with open(filename, 'w') as f:
     for sublist in lst:
          line = "{}, {}\n".format(sublist[0], sublist[1])
          f.write(line)

写入文件的输出:

a, 2.0
b, 3.0
c, 4.0