简体   繁体   English

在python中将列表写入CSV

[英]Write lists to csv in python

I have this list list of values: 我有此值列表:

Output of list_a: list_a的输出:

list_a: [[[2.0, 4.0], [1.0, 2.0]], [[2.0, 4.0], [2.0, 3.0], [3.0, 1.0]], [[3.0, 6.0], [5.0, 5.0], [6.0, 4.0]], [[3.0, 6.0], [4.0, 7.0]], [[2.0, 4.0], [3.0, 6.0]]]

I want to export it to a csv file in a specific format so that every set of values occupies a cell in the following format: 我想将其导出为特定格式的csv文件,以便每组值以以下格式占用一个单元格:

 (2.0; 4.0) | (1.0; 2.0)
 (2.0; 4.0) | (2.0; 3.0) | (3.0; 1.0)
 ...

The "|" “ |” represents the separation of cells on the same row (not to be included in the csv file) and the format of the values in the cell should be parentheses and semicolon as such (X1; X2) 表示同一行上的单元格分隔(不包含在csv文件中),并且单元格中值的格式应为括号和分号,例如(X1; X2)

I tried the following but I get brackets and colons: 我尝试了以下操作,但得到了方括号和冒号:

with open('outputdata.csv', 'w') as outfile:
    mywriter = csv.writer(outfile)

    for d in result:
        mywriter.writerow(d)

Any help is appreciated! 任何帮助表示赞赏!

It may be easier to generate the output file without the writer: 如果没有编写器,生成输出文件可能会更容易:

SEP = ',' # Use any other separator here, if you want
with open('outputdata.csv', 'w') as outfile:
   for line in list_a:
      outfile.write(SEP.join(['({}; {})'.format(*pair) for pair in line]))
      outfile.write("\n")

You can try to write the csv yourself, without any writer class: 您可以尝试自己编写csv,而无需任何writer类:

with open('outputdata.csv', 'w') as f:
    for vector in list_a:
        len_ = len(vector)
        for i, point in enumerate(vector):
            f.write("({}; {})".format(*point))
            # avoid writing the last pipe
            if i != len_ - 1:
                f.write(" | ")
        f.write("\n")

Contents: 内容:

(2.0; 4.0) | (1.0; 2.0)
(2.0; 4.0) | (2.0; 3.0) | (3.0; 1.0)
(3.0; 6.0) | (5.0; 5.0) | (6.0; 4.0)
(3.0; 6.0) | (4.0; 7.0)
(2.0; 4.0) | (3.0; 6.0)

try this: 尝试这个:

with open('outputdata.csv', 'w') as outfile:
    mywriter = csv.writer(outfile)
    for d in result:
        row = ' | '.join(['(%f; %f)' % (t[0], t[1]) for t in d])
        mywriter.writerow(d)

Each element of each row is an array of of two floats, right? 每行的每个元素都是两个浮点数的数组,对吗? So, we use a format string to convert [2.0, 4.0] to "(2.0; 4.0)" . 因此,我们使用格式字符串将[2.0, 4.0]转换为"(2.0; 4.0)" We do this for every tuple in the row. 我们针对行中的每个元组执行此操作。 Then, we just use python's join() function to put the characters | 然后,我们只使用python的join()函数来放置字符| between them and link them all into one string, which we can write to the file. 在它们之间并将它们链接成一个字符串,我们可以将其写入文件。

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

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