从csv文件到列表中选择n个随机行的最快方法是什么?

时间:2017-07-04 10:57:38

标签: python

我有以下方法:

ids = random.sample(list(map(int, open(file_path))), 10)

返回10个随机整数的列表。

如何加快速度?另外一种方法是什么?

1 个答案:

答案 0 :(得分:0)

在我看来,挂断总是会找到文件的长度。请参阅How to get line count cheaply in Python?

然后你可以做

import random

lines = random.sample(range(length_of_file), 10)

with open(file) as f:
    lines_from_file = [f.readline(line) for line in lines]

或类似的东西。这与速度相比如何?