簡體   English   中英

在python中將列表寫入CSV

[英]Write lists to csv in python

我有此值列表:

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]]]

我想將其導出為特定格式的csv文件,以便每組值以以下格式占用一個單元格:

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

“ |” 表示同一行上的單元格分隔(不包含在csv文件中),並且單元格中值的格式應為括號和分號,例如(X1; X2)

我嘗試了以下操作,但得到了方括號和冒號:

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

    for d in result:
        mywriter.writerow(d)

任何幫助表示贊賞!

如果沒有編寫器,生成輸出文件可能會更容易:

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

您可以嘗試自己編寫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")

內容:

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

嘗試這個:

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)

每行的每個元素都是兩個浮點數的數組,對嗎? 因此,我們使用格式字符串將[2.0, 4.0]轉換為"(2.0; 4.0)" 我們針對行中的每個元組執行此操作。 然后,我們只使用python的join()函數來放置字符| 在它們之間並將它們鏈接成一個字符串,我們可以將其寫入文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM