简体   繁体   English

将文件写入元组列表

[英]writing a file to a list of tuples

I am trying to read a file and write its contents to a list of tuples. 我正在尝试读取文件并将其内容写入元组列表。 the length of each tuple is 2 and the length of the list is variable depending on which file we read from. 每个元组的长度是2,列表的长度是可变的,具体取决于我们从哪个文件中读取。 Each tuple should represent a point in the x, y plane with the first value being the x coord and the second the y. 每个元组应表示x,y平面中的一个点,第一个值为x坐标,第二个为y。 The issue I am having is that I believe a for loop is the best way to do this but the first line in the file is a single value representing how many points are in the file and should not be included in the final list at all. 我遇到的问题是,我相信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

An example of an input is: 输入的示例是:

10 10
96 571 96571
45 734 45734
174 416 174416
357 259 357259
88 97 88 97
188 495 188495
348 443 348443
301 503 301503
719 177 719177
182 237 182237

and the output should be: 输出应为:

[(96, 571), (45, 734), (174, 416), (357, 259), (88, 97).....]

Is there a way to start the for loop from the second line? 有没有办法从第二行开始for循环? or is there an easier way to solve this? 还是有更简单的方法来解决这个问题?

Thanks 谢谢

You can call next on the file object to skip the first line and start at the second then either split each line and call tuple or let the csv.reader parse each row and map to tuple: 您可以在文件对象上调用next来跳过第一行并从第二行开始,然后拆分每一行并调用元组,或者让csv.reader解析每一行并映射到元组:

splitting: 分裂:

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

csv lib: csv库:

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

Both will return: 两者都将返回:

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

If you want ints: 如果您想要整数:

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

And the csv.reader: 和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)

Which will give you: 这会给你:

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

You can use .split() to create the tuple out of each line and check the length: 您可以使用.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

You can use tell the loop to only iterate over lines[1:] which will skip the first line and use all the rest. 您可以使用tell循环仅对lines [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

Just another idea. 只是另一个想法。

with open('in.txt') as f:
    nums = map(int, f.read().split())
    print zip(nums[1::2], nums[2::2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM