【问题标题】:randomly subsampling lines in a file随机对文件中的行进行二次采样
【发布时间】:2015-05-31 15:56:47
【问题描述】:

我有一个这样的文件:

Tree 5
Jaguar 9
Cat 23
Monkey 12
Gorilla 67

是否可以对这些行中的 3 行进行随机二次抽样? 例如:

Jaguar 9
Gorilla 67
Tree 5

Monkey 12
Tree 5
Cat 23

等等?

【问题讨论】:

    标签: python


    【解决方案1】:

    readlines 上使用random.sample

    import random
    
    random.sample(open('foo.txt', 'r').readlines(), 3)
    

    【讨论】:

    • 这是最有效的方法吗?特别是如果有大量数据?提前致谢
    • @Noah16 对于大文件,您可能需要reservoir sampling
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2021-02-17
    相关资源
    最近更新 更多