I am new to python and i am trying to import a set of x,y coordinates from csv into 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):
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)我希望它们全部独立,因此可以迭代公式
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.