简体   繁体   English

将子列表的列表写入文件中,不带括号,并用“;”分隔

[英]Writing list of sublists into file without brackets and separated with “;”

I'm new here (and also in python) so tell me if I do something wrong. 我在这里是新手(也是python),所以请告诉我我做错了什么。 I have a little (I think) problem: I have a list of sublists where all variables (x) are float: 我有一个小问题(我认为):我有一个子列表,其中所有变量(x)都是浮动的:

tab=[[x11,x12,x13],[x21,x22,x23]]

And I wanto to write to the *txt file without brackets [] and separated by ";" 我想写到不带方括号[]并以“;”分隔的* txt文件中 like this: 像这样:

x11;x12;x13 x11; x12; x13

x21;x22;x23 x21; x22; x23

I tried to do it like this: but i have no idea what should I do next. 我试图这样做:但是我不知道下一步该怎么做。

tab=[[x11,x12,x13],[x21,x22,x23]]
result=open("result.txt","w")
result.write("\n".join(map(lambda x: str(x), tab)))
result.close()

A lot of thanks for everyone who will try to help me. 非常感谢所有尝试帮助我的人。

You can use the csv module for this: 您可以为此使用csv模块

import csv

with open("result.txt", "wb") as result:
    writer = csv.writer(result, delimiter=';')
    writer.writerows(tab)

The csv.writer.writerows() method takes a list of lists, and converts floating point values to strings for you. csv.writer.writerows()方法获取列表列表,然后为您将浮点值转换为字符串。

You should use this: 您应该使用此:

result.write("\n".join([';'.join([str(x) for x in item]) for item in tab]))

Or, little simpler: 或者,简单一点:

result.write("\n".join([';'.join(map(str, item)) for item in tab]))

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

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