[英]I need to get tuples of x,y coordinates from a file and add it to a list
所以我的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'以及如何将列表中的每个元素放入一个元组。 谢谢。 我没有加入尝试的错误。
这是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]
就像IljaEverilä指出的那样,“打开文件作为迭代器”更好:
with open("my_txt_file") as f:
result = [tuple(int(s) for s in line.strip().split(",")) for line in f]
从文件中换行读取所有内容。 从每个字符串中删除换行符。 然后通过用逗号分割将每个字符串转换为元组。 以下是带有文本文件输入的代码,其中包含您所要求的内容和预期的结果。
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)]
希望这会有所帮助。 :-)
由于文件包含逗号分隔的整数值,因此可以使用csv
模块来处理它:
import csv
with open(filename, newline='') as f:
reader = csv.reader(f)
numbers = [tuple(map(int, row)) for row in reader]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.