【问题标题】:I need to get tuples of x,y coordinates from a file and add it to a list我需要从文件中获取 x,y 坐标的元组并将其添加到列表中
【发布时间】:2016-10-01 18:55:02
【问题描述】:

所以我的 txt 文件看起来像这样:

68,125
113,69
65,86
108,149
152,53
78,90
54,160
20,137
107,90
48,12

我需要读取这些文件,然后将其放入 x 和 y 坐标元组列表中。

我的输出应该是

[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53), (78, 90), (54, 160), (20, 137), (107, 90), (48, 12)] 

我被困在如何做到这一点上。我只需要使用基本的python。

编辑:

到目前为止我的尝试是这样的

numbers = []
input_file = open(filename,'r')
numbers_list = input_file.readlines()
input_file.close()
for i in numbers_list:
    numbers += [i]
return numbers

我的输出返回如下:

['68,125\n', '113,69\n', '65,86\n', '108,149\n', '152,53\n', '78,90\n', '54,160\n', '20,137\n', '107,90\n', '48,12\n']

如何摆脱 '\n' 以及如何将列表中的每个单独元素放入一个元组中。谢谢你。我的错误是没有加入我的尝试。

【问题讨论】:

  • 你尝试了什么?
  • 对不起,我应该这样做

标签: python list file python-3.x tuples


【解决方案1】:

在文件换行的基础上读取所有内容。 从每个字符串中去除换行符。 然后通过逗号分割将每个字符串转换为元组。 下面是带有文本文件输入的代码,其内容符合您的要求,结果符合您的预期。

import sys
def test(filename):
    f = open(filename)
    lines = f.readlines()
    lines = [item.rstrip("\n") for item in lines]
    newList = list()
    for item in lines:
            item = item.split(",")
            item = tuple(int(items) for items in item)
            newList.append(item)                
    f.close()
    print newList

if __name__ == "__main__":
    test(sys.argv[1])

O/P:
techie@gateway2:myExperiments$ python test.py /export/home/techie/myExperiments/test.txt
[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53), (78, 90), (54, 160), (20, 137), (107, 90), (48, 12)]

希望这会有所帮助。 :-)

【讨论】:

  • 我怎样才能用这种方法去掉引号(“ ' ”)。
  • 好的。我猜你想要整数元组??
  • 是的,我应该指定的。
  • 好的,我已根据您的要求编辑了答案。请看答案。我们可以用更 Pythonic 的方式在两行代码中完成这些事情。但我认为这会更容易理解,这就是为什么给出简单的代码。
  • 这个特定的代码给出了索引错误“IndexError: list index out of range”,请帮忙!!
【解决方案2】:

这里有 3 行和 2 行答案:

with open("my_txt_file") as f:
  lines = f.readlines()
result = [tuple(int(s) for s in line.strip().split(",")) for line in lines]

正如 Ilja Everilä 指出的那样,“作为迭代器打开文件”更好:

with open("my_txt_file") as f:
  result = [tuple(int(s) for s in line.strip().split(",")) for line in f]

【讨论】:

  • 如果您必须从文件中读取行并立即处理它们,您应该几乎总是避免使用readlines()。只需将打开的文件用作迭代器。您为列表理解创建了一个不必要的列表副本,因为您没有改变其中的列表 linessplit()[0] 很奇怪,你的意思是 strip()
  • @IljaEverilä 感谢您的建议!编辑了答案
【解决方案3】:

由于您的文件包含逗号分隔的整数值,您可以使用csv 模块来处理它:

import csv

with open(filename, newline='') as f:
    reader = csv.reader(f)
    numbers = [tuple(map(int, row)) for row in reader]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多