我正在尝试读取一个文件并将其内容写入元组列表。每个元组的长度为 2,列表的长度根据我们读取的文件而变化。每个元组应代表 x、y 平面中的一个点,第一个值是 x 坐标,第二个值是 y 坐标。我遇到的问题是,我相信 for 循环是执行此操作的最佳方法,但文件中的第一行是表示文件中有多少个点的单个值,根本不应该包含在最终列表中。
def readDataPts(filename):
"""Reads data from an input file and returns a list of tuples
[(x0,y0), (x1, y1), ...]
"""
file = open(filename, 'r')
lines = file.readlines()
listPts = []
for line in lines:
for ptx, pty in line:
x = (ptx, pty)
listPts.append(x)
return listPts
输入的示例是:
10
96571
45 734
174 416
357 259
88 97
188 495
348 443
301 503
719 177
182237
输出应该是:
[(96, 571), (45, 734), (174, 416), (357, 259), (88, 97).....]
有没有办法从第二行开始for循环?或者有更简单的方法来解决这个问题吗?
谢谢
最佳答案
您可以使用.split()
从每行创建元组并检查长度:
def readDataPts(filename):
listPts = []
with open(filename, 'r') as f:
for line in f:
numbers = line.split()
if len(numbers) == 2:
listPts.append(map(int, numbers))
return listPts
关于python - 将文件写入元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174497/