简体   繁体   English

用元组编写列表列表的csv

[英]Writing csv of list of lists with tuples

I have this data - 我有这个数据 -

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

The tuples inside the inner list are co-ordinates. 内部列表中的元组是坐标。

I've tried this - 我试过这个 -

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

The file contains this output - 该文件包含此输出 -

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

I tried reading from this file using this - 我尝试使用此文件从此文件中读取 -

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

Gave me [] 给了我[]

And there can be multiple tuples in the inner list. 并且内部列表中可以有多个元组。
How can I write this to file as csv, such that another python program can read it? 如何将此文件作为csv写入文件,以便另一个python程序可以读取它?

Perhaps something like this? 也许是这样的?

#!/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])

I think this might be what you want. 我想这可能是你想要的。 I changed to data to have more than one tuple on one of the inner lists and have more unique values to aid troubleshooting. 我更改为数据以在其中一个内部列表上具有多个元组,并具有更多唯一值以帮助进行故障排除。 The important point is that you must pass writerows() a sequence of strings or numbers (or apparently a generator expression producing such things). 最重要的一点是,你必须通过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"))]

Output: 输出:

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

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

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