python从文件的每一行中随机选择

时间:2017-06-02 14:32:09

标签: python numpy random

我想从文本文件的每一行中随机选择3个元素:

6717108 8373270 8670842 8671024 8671040 
8671069 8672185 
8672302 8672317 8672363 8672481 8672533 8672550 8672587 
8672610 
8672611 8672640 8672661 8672684 8688747 8688760 8688777 8688792 8688827 
8688836 8688884 8689003 8689037 
8672233 8688891 8688908 
8688971 8689078 

但是,我在每一行中并不总是有3个元素,在这种情况下,它应该占用所有元素。 因此输出将是随机的:

6717108 8670842 8671040 
8671069 8672185 
8672317 8672481 8672533
8672610 
8672611 8688747 8688760 
8688836 8689003 8689037 
8672233 8688891 8688908 
8688971 8689078 

我的尝试如下:

random_list = []
with open('my_inputFile', "r") as myFile:
    for line in myFile.readlines():
        myparts = line.split(' ')
        random_list.append(np.random.choice(myparts, 3))

输出格式将以列表形式出现:

6717108
8670842
8671040
8671069
8672185
8672317
8672481
8672533
8672610
8672611
8688747
8688760
8688836
8689003
8689037
8672233
8688891
8688908
8688971
8689078

问题是:

我的代码在每行中少于3个元素时不满足条件,并且它显然不是列表格式。

3 个答案:

答案 0 :(得分:4)

如果一行中有三个以上的元素,则只需要随机绘制。 而且你的代码样本"有替换",这意味着它可以绘制相同的值两次(甚至三次)。所以添加标记replace=False,或者更好,只需使用random.sample();你不需要numpy

for line in myFile.readlines():
    myparts = line.split()
    if len(myparts) > 3:
        random_list.append(random.sample(myparts, 3))
    else:
        random_list.append(myparts)

您不清楚输出的问题是什么,但您以此方式创建的random_list是一个列表列表。您可以随意打印出来。

答案 1 :(得分:2)

如果你想在最后找到一个平面列表,你需要扩展方法,如果你不想多次选择一个项目,还需要指定replace=False

random_list = []
​
with open('pathToFile/inputFile', 'r') as f:
    for line in f.readlines():
        myparts = line.strip().split(' ')
        if len(myparts) <= 3:
            random_list.extend(myparts)
        else:
            random_list.extend(np.random.choice(myparts, 3, replace=False))

random_list
['8670842',
 '6717108',
 '8671024',
 '8671069',
 '8672185',
 '8672363',
 '8672317',
 '8672587',
 '8672610',
 '8688827',
 '8672661',
 '8688792',
 '8688884',
 '8689037',
 '8689003',
 '8672233',
 '8688891',
 '8688908',
 '8688971',
 '8689078']

答案 2 :(得分:1)

import random

random_list = []
with open('my_inputFile', "r") as myFile:
    for line in myFile.readlines():
        myparts = line.split(' ')
        l=len(myparts)
        if l< 4:
           random_list+=myparts
        else:
           for i in range(0,3):
               random_list+=[ myparts.pop(random.randrange(l))]
               l-=1

应该这样做。