【问题标题】:writing a file to a list of tuples将文件写入元组列表
【发布时间】:2016-09-07 13:19:03
【问题描述】:

我正在尝试读取文件并将其内容写入元组列表。每个元组的长度是 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
357 259
88 97
188 495
348 443
301 503
719 177
182 237

输出应该是:

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

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

谢谢

【问题讨论】:

    标签: python list file for-loop tuples


    【解决方案1】:

    只是另一个想法。

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

    【讨论】:

      【解决方案2】:

      您可以在文件对象上调用 next 以跳过第一行并从第二行开始,然后拆分每一行并调用元组或让 csv.reader 解析每行并映射到元组:

      拆分:

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

      csv 库:

      import  csv
      with open("in.txt") as f:
          next(f) # skip first line
          arr = list(map(tuple, 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')]
      

      如果你想要整数:

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

      还有 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() 函数
      • 不用担心,一个文件对象返回它自己的迭代器,一旦你在它上面调用下一个,你就移动到第二行,所以没有必要做任何其他事情 bar split 和 cast to tuple,如果你是好的列表只是拆分
      【解决方案3】:

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

      【讨论】:

      • 谢谢你,太棒了。我什至没想过要使用 .split() 干杯
      【解决方案4】:

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

      【讨论】:

      • 感谢您的回复。我从来不知道你可以为这样的 for 循环提供索引。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多