通过python将列表列表写入COLUMNED .txt文件

时间:2018-02-22 08:03:59

标签: python list

我有一个类似于

的列表
[["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]

如何将此列表列表转换为类似

的文本文件
a  b  c  d
e  f  g  h
i  j  k  l

这似乎很简单,但网上的解决方案似乎都不够简洁,也不足以让我这样的假人理解。

谢谢!

6 个答案:

答案 0 :(得分:6)

赞美理解的力量:

lst = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]

out = "\n".join([" ".join(sublist) for sublist in lst])
print(out)

这会产生

a b c d
e f g h
i j k l

或者,更长,也许更容易理解:

for sublist in lst:
    line = " ".join(sublist)
    print(line)

<小时/> 如果您的元素具有不同的长度,则可以使用.format()

lst = [["a","b","cde","d"],["e","f","g","h"],["i","j","k","l"]]

out = "\n".join(["".join("{:>5}".format(item) for item in sublst) for sublst in lst])
print(out)

哪会产生

a    b  cde    d
e    f    g    h
i    j    k    l

答案 1 :(得分:4)

您可以将列表理解与换行符一起使用:

'\n'.join(' '.join(item) for item in ls)

答案 2 :(得分:4)

发布只是为了突出您需要采取的步骤

l = [['a','b','c','d'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
with open('my_file.txt', 'w') as f:
    for sub_list in l:
        for elem in sub_list:
            f.write(elem + ' ')
        f.write('\n')

答案 3 :(得分:2)

要以该格式写入文件,您可以使用join,如下所示:

array = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l']]

# create a file if not exist and open it
file = open('testfile.txt', 'w')

# for each element in the array
for a in array: 
    # convert each sub list to a string, and write it in the file, note break line '\n'
    file.write(' '.join(a) + '\n') 

# close the file when you finish
file.close()

结果:

write in a file

为了避免最后的断行,你可以使用:

breakLine = ''
for a in array:
    file.write(breakLine + ' '.join(a))
    # Use break line after the first write
    breakLine = '\n'
file.close()

结果2

write in a file

答案 4 :(得分:1)

那里有csv。

l = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]

with open("test.csv", 'w', encoding="utf-8", newline="") as f:
    writer = csv.writer(f, delimiter=' ')# or "\t", default is coma.
    writer.writerows(l)

答案 5 :(得分:1)

更多一个衬垫,为了好玩 (不要像这样编写代码!)

with open('/tmp/my_file2.txt', 'w') as thefile: thefile.write('\n'.join(' '.join(el for el in l1) for sub in sub))