将文件写入元组列表

2024-04-24 14:58:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取文件并将其内容写入元组列表。每个元组的长度是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
96 571
45 734
174 416
357259
88 97
188 495
348 443
301 503
719 177
182 237号

输出应为:

^{pr2}$

有没有办法从第二行开始for循环?还是有更简单的方法来解决这个问题?在

谢谢


Tags: 文件方法in内容列表forlinefilename
3条回答

可以使用tell the loop只迭代行[1:],这将跳过第一行并使用其余的行。在

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[1:]:
        for ptx, pty in line:
            x = (ptx, pty)
        listPts.append(x)
    return listPts

您可以在file对象上调用next跳过第一行,从第二行开始,然后拆分每一行并调用tuple,或者让csv.reader要分析并映射每一行:

拆分:

with open("in.txt") as f:
    next(f) # skip first line
    arr = [tuple(line.split()) for line in f]
    print(arr)

csv库:

^{pr2}$

两者都将返回:

[('96', '571'), ('45', '734'), ('174', '416'), ('357', '259'), ('88', '97'), ('188', '495'), ('348', '443'), ('301', '503'), ('719', '177'), ('182', '237')]

如果需要整数:

^{4}$

以及csv.reader公司名称:

import  csv
with open("in.txt") as f:
    next(f) # skip first line
    arr = [tuple(map(int,row) for row in  csv.reader(f,delimiter=" "))]
    print(arr)

这会给你:

 [(96, 571), (45, 734), (174, 416), (357, 259), (88, 97), (188, 495), (348, 443), (301, 503), (719, 177), (182, 237

您可以使用.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

相关问题 更多 >