简体   繁体   English

从 CSV 导入坐标 - Python

[英]Importing coordinates from CSV - Python

I am new to python and i am trying to import a set of x,y coordinates from csv into python.我是 python 的新手,我正在尝试将一组 x,y 坐标从 csv 导入 python。

currently my script looks as below:目前我的脚本如下所示:

with open ('filename.csv') as csvfile:
    data = list(tuple(rec) for rec in csv.reader(csvfile, delimiter= ","))

this provides me with a list of coords as below (when printed):这为我提供了如下的坐标列表(打印时):

[('1', '2'), ('5', '6'), ('4', '4'), ('8', '9')]

However i need the output to look as below so that it can be passed successfully into a point in polygon test.但是我需要输出如下所示,以便它可以成功传递到多边形测试中的一个点。

[(1, 2), (5, 6), (4, 4), (8, 9)]

Can anyone recommend how i would change my script to achieve the result above?任何人都可以推荐我如何更改脚本以实现上述结果?

Many ways to do it, but I think this is the shortest (when using the csv module, with just a open alone it could be shorter):有很多方法可以做到,但我认为这是最短的(当使用 csv 模块时,只有一个open可能会更短):

with open('filename.csv') as csvfile:
    data = [(int(x), int(y)) for x, y in csv.reader(csvfile, delimiter= ',')]
import csv

with open('coords.csv', 'rb') as csvfile:
    data = [tuple(map(int, row)) for row in csv.reader(csvfile)]

print data

You could also do it incrementally using a generator function and avoid creating a huge list (unless that's your goal):您也可以使用生成器函数逐步执行此操作并避免创建庞大的列表(除非这是您的目标):

def get_data(filename):
    with open(filename, 'rb') as csvfile:
        for x, y in csv.reader(csvfile):
            yield int(x), int(y)

print list(get_data('coords.csv'))

Either way, this would be the output:无论哪种方式,这将是输出:

[(1, 2), (5, 6), (4, 4), (8, 9)]

试试这个:

[(int(x), int(y)) for x, y in l]

我怎样才能使每个坐标都像这样排成一行:1.(1,2)2.(3,4)3.(4,5)我希望它们全部独立,因此可以迭代公式

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

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