python 3 : How to best iterate over all lines in a big file (+1 million lines) in a random order

标签 python python-3.x loops random shuffle

好的,所以我有多个文本文件,每个文本文件包含超过 500.000 甚至 1.000.000 行。

目前我在做这样的事情:

import random

def line_function(line):
    # Do something with given line

def random_itteration(filepath):
    with open(filepath) as f:
        lines = f.readlines()
        random.shuffle(lines)
        for line in lines:
            result = line_function(line)

问题是 Python Docsrandom.shuffle() 上明确指出(重点是我加的):

Note that even for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.

那么问题是:

让我的设置按预期工作的最快和最有效的方法是什么?

更多信息:

我想将 line_function() 应用于随机行而不是简单地按它们所在的顺序迭代它们是有原因的。另请注意,我非常喜欢只处理每行一次.

最后,不幸的是,预先打乱文本文件或将其分成较小的文件不是一种选择。这不是我要问的。


欢迎任何见解!提前谢谢大家。

最佳答案

正如 Mark Dickinson 所说,您引用的文档行对实际代码基本上没有实际意义。它绝对与您的代码没有任何关系。

洗牌是否对所有可能的排列产生真正均匀的随机分布并不重要。重要的是洗牌是否可以从这样的分布中区分,达到某种区分标准。 random.shuffle 在统计上无法与完美随机洗牌区分开来,直到底层 Mersenne Twister 算法的质量,并且它的区分方式与周期无关。

您无需执行任何特殊操作即可使您的设置“按预期工作”。 random.shuffle 已经有效。

关于 python 3 : How to best iterate over all lines in a big file (+1 million lines) in a random order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49014601/

相关文章:

python - 如何找到在 Graphlab SFrame 中保存时引发错误的特定行?

python - 生成排列

python - 如果我使用 GridsearchCV,如何在 Xgboost 中使用 model.evals_result()?

python - 子类在sqlAlchemy中按条件过滤父类

python - 如何使用 pyzmq 发送带有 PUB/SUB 模式的字典?

python - 根据对角线项对矩阵进行排序

javascript - 通过 .map 循环创建按钮时出现问题

Python:将多行用户输入写入文本文件

r - 使用 if 语句对数字进行分类的循环

r - 算法效率——时差循环