【问题标题】:Importing coordinates from CSV - Python从 CSV 导入坐标 - Python
【发布时间】:2013-12-18 16:00:44
【问题描述】:

我是 python 新手,我正在尝试将一组 x,y 坐标从 csv 导入 python。

目前我的脚本如下所示:

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

这为我提供了如下坐标列表(打印时):

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

但是我需要输出如下所示,以便它可以成功地传递到多边形测试中的一个点。

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

谁能推荐我将如何更改我的脚本以实现上述结果?

【问题讨论】:

  • 注:如果你使用的是 Python 2,它应该是open('filename.csv','rb'); Python 3,open('filename.csv', 'r', newline='').
  • 另外,csv.reader() 调用中的 delimiter="," 不是必需的,因为毫不奇怪,这是 CSV (Comma-separated values) 的默认值。

标签: python csv tuples


【解决方案1】:

有很多方法,但我认为这是最短的(使用 csv 模块时,仅使用 open 可能会更短):

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

【讨论】:

  • 太好了,我在最后添加了一个方括号并删除了重复的“in”,它完成了工作!
  • 哎呀...我写的时候显然没有注意。很高兴它对你有用:)
【解决方案2】:
import csv

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

print data

您也可以使用生成器函数逐步执行此操作,并避免创建庞大的列表(除非这是您的目标):

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'))

不管怎样,这将是输出:

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

【讨论】:

    【解决方案3】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2022-01-09
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多