簡體   English   中英

用元組編寫列表列表的csv

[英]Writing csv of list of lists with tuples

我有這個數據 -

data = [[(1,2)], [(1,2)], [(1,2)]]

內部列表中的元組是坐標。

我試過這個 -

>>> with open("file.csv", "wb") as afile:
...   writer = csv.writer(afile)
...   writer.writerows(data)

該文件包含此輸出 -

"(1, 2)"
"(1, 2)"
"(1, 2)"

我嘗試使用此文件從此文件中讀取 -

print [row for row in csv.reader(open("file.csv", "rb"))]

給了我[]

並且內部列表中可以有多個元組。
如何將此文件作為csv寫入文件,以便另一個python程序可以讀取它?

也許是這樣的?

#!/usr/local/cpython-3.3/bin/python

import csv

data = [[(1,2)], [(1,2)], [(1,2)]]

with open("file.csv", "w") as afile:
    writer = csv.writer(afile)
    for sublist in data:
        writer.writerow(sublist[0])

我想這可能是你想要的。 我更改為數據以在其中一個內部列表上具有多個元組,並具有更多唯一值以幫助進行故障排除。 最重要的一點是,你必須通過writerows()字符串或數字序列(或表面生成器表達式生成這樣的事情)。

import csv

data = [[(1,1)], [(1,2), (3,4)], [(1,3)]]

with open("file.csv", "wb") as afile:
    writer = csv.writer(afile)
    writer.writerows((coord for coord in data))

print [row for row in csv.reader(open("file.csv", "rb"))]

輸出:

[['(1, 1)'], ['(1, 2)', '(3, 4)'], ['(1, 3)']]

暫無
暫無

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

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