【问题标题】:Python: reading N number from file, M at timePython:从文件中读取N个数字,一次M
【发布时间】:2016-05-15 18:24:32
【问题描述】:

我的文件是这个:

14
3
21
37
48
12
4
6
22
4

如何读取 M 数?例如一次 4 个。有必要使用两个 for 循环吗?

我的目标是创建 (N/M)+1 个列表,每个列表中都有 M 个数字,除了最终列表(这是 N/M 分区的提醒)

【问题讨论】:

  • 您是否尝试过使用两个for 循环来实现它?这将是一个很好的起点,如果您遇到问题,可以寻求帮助。
  • 我编辑了我的答案。请检查一下。

标签: python file io


【解决方案1】:

您可以使用 python list slice 运算符通过使用 readlines() 读取文件来从文件中获取所需元素的数量,其中列表的每个元素将是一行文件。

with open("filename") as myfile:
    firstNtoMlines = myfile.readlines()[N:N+M] # the interval you want to read
    print firstNtoMlines

【讨论】:

  • 我已经尝试过这个解决方案。我已经把它放到了一个while循环中
  • 是的,它应该可以工作,我的代码在这个上面的帖子中
【解决方案2】:

使用itertools.islice

import itertools 
import math

filename = 'test.dat'
N = 9
M = 4

num_rest_lines = N
nrof_lists = int(math.ceil(N*1.0/M))

with open(filename, 'r') as f:
    for i in range(nrof_lists):
        num_lines = min(num_rest_lines, M)
        lines_gen =  itertools.islice(f, num_lines)

        l = [int(line.rstrip()) for line in lines_gen]
        num_rest_lines = num_rest_lines - M

        print(l)    
        # Output
        [14, 3, 21, 37]
        [48, 12, 4, 6]
        [22]

上一个答案:以块(每 M 行)遍历文件(N 行),形成N/M+1 列表的列表。

import itertools 

def grouper(iterable, n, fillvalue=None):
    """iterate in chunks"""
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

# Test
filename = 'test.dat'
m = 4
fillvalue = '0'

with open(filename, 'r') as f:
    lists = [[int(item.rstrip()) for item in chuck] for chuck in grouper(f, m, fillvalue=fillvalue)]
    print(lists)
    # Output
    [[14, 3, 21, 37], [48, 12, 4, 6], [22, 4, 0, 0]]

【讨论】:

  • 我不知道为什么我导入 itertools 时没有出现 izip_longest 方法。我用蟒蛇。我不能叫它
  • 我输入“从 itertools 导入...”但 Eclispe 没有找到 izip_method。没有错误,就是这个
  • @LorenzoVannucchi,如果通过from itertools import izip_longest 导入模块,则itertools.izip_longest 这一行应替换为izip_longest`。
【解决方案3】:

现在我的代码是这个:

N = 4
M = 0

while (M < 633):
    with open("/Users/Lorenzo/Desktop/X","r") as myFile:
        res = myFile.readlines()[M:N]
        print(res)
    M+=4
    N+=4

所以,它应该工作。我的文件有 633 个号码

【讨论】:

    【解决方案4】:

    以前有人问过这个问题。

    from itertools import izip_longest
    izip_longest(*(iter(yourlist),) * yourgroupsize)
    

    对于将文件中的行分组为大小为 4 的列表的情况:

    with open("file.txt", "r") as f:
        res = izip_longest(*(iter(f)),) * 4)
        print res
    

    Alternative way to split a list into groups of n

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2014-04-14
      • 1970-01-01
      • 2017-06-15
      相关资源
      最近更新 更多