简体   繁体   中英

Write lists to csv in python

I have this list list of values:

Output of 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:

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

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:

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)" . We do this for every tuple in the row. Then, we just use python's join() function to put the characters | between them and link them all into one string, which we can write to the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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