jeudi 21 novembre 2019

Randomize strings from a list with constraints on string beginning python

I have a list RIR_list of filenames of the form number/filename. For example 3/foo. The numbers are integers from 1-30 in this case (without loss of generality).

I wish to choose a sub-list of n pairs out of the previous list. Each of the n pairs should have the same number at the beginning for both entries. Valid code for this is (if I have missed nothing):

#choose a random beginning for each pair    
room_nb = np.random.randint(30,size=n)+1
#iterate through pairs
for i in range(n): 
    #generate sublist containing only entries with the correct beginning for this iteration
    room_RIR = [rir for rir in RIR_list if rir.startswith(str(room_nb[i])+'/')] 
    #pick a random pair with the same header for this iteration
    chosen_RIR = random.choices(room_RIR, k=2)

If I only wished to randomize n entries, I could do with a one-liner random.choices(RIR_list, k=n) twice for pairs. Is there a way to do the fool job in a more elegant way? More importantly, maybe a lower computation?




Aucun commentaire:

Enregistrer un commentaire