我有一个.csv文件,其中包含其他信息中的x / y坐标。
我需要提取x / y坐标信息以提供给另一个包。该包接受一个元组列表,其中元组包含整数)例如。 [(1,2),(3,4)]
rdpList = []
with open ('test.csv', 'rb') as fp_in
reader = csv.reader(fp_in, delimiter = ',')
for row in reader:
del row[0:4] #trimmming to column with x coordinates
del row[2:] #trimming to column with y coordinate
rdpList.append(tuple(row))
这让我关闭了我需要的结果,但是元组中的数据类型是字符串。例如[('1','2'),('3','4')]
尝试
rdpList = []
with open ('test.csv', 'rb') as fp_in
reader = csv.reader(fp_in, delimiter = ',')
for row in reader:
del row[0:4]
del row[2:]
rdpList.append(tuple(int(x) for x in tup) for tup in row)
给了我
[<generator object <genexpr> at 0x7f36452e1a00>, <generator object <genexpr> at 0x7f36452e1a50>]
尝试
rdpList = []
with open ('test.csv', 'rb') as fp_in
reader = csv.reader(fp_in, delimiter = ',')
for row in reader:
del row[0:4]
del row[2:]
for y in row:
int(y)
rdpList.append(tuple(row))
给了我
ValueError: invalid literal for int() with base 10: 'x'
尝试
rdpList = []
with open ('test.csv', 'rb') as fp_in
reader = csv.reader(fp_in, delimiter = ',')
for row in reader:
del row[0:4]
del row[2:]
rdpList.append(tuple(map(int, row.split(','))))
给了我
AttributeError: 'list' object has no attribute 'split'
我怎样才能得到我想要的结果? .csv文件的状态并不重要,只有rdpList []很重要,
答案 0 :(得分:0)
从您的示例中,看起来坐标位于第5和第6列。假设文件如:
a,b,c,d,1,2,e,f
a,b,c,d,3,4,e,f
a,b,c,d,5,6,e,f
这就是你所需要的:
import csv
with open ('test.csv', 'rb') as fp_in:
reader = csv.reader(fp_in)
rdpList = [(int(row[4]),int(row[5])) for row in reader]
print rdpList
输出:
[(1, 2), (3, 4), (5, 6)]