Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create 2 random lists based on 1 list?

I have a global_list: [1,7,23,72,7,83,60]
I need to create to 2 randoms lists from this one (example):

  • list_1: [7, 7, 23, 83, 72]
  • list_2: [1, 60]

My actual working code is:

import random
import copy

def get_2_random_list(global_list, repartition):
    list_1, list_2 = [], copy.copy(global_list)
    list_1_len = round(len(list_2)*repartition)
    print("nbr of element in list_1:",list_1_len)
    for _ in range(list_1_len):
        index = random.randint(1,len(list_2)-1)
        list_1.append(list_2[index])
        del list_2[index]
    return list_1, list_2


global_list = [1,7,23,72,7,83,60]
list_1,list_2 = get_2_random_list(global_list,0.7)
print("list_1:", list_1)
print("list_2:", list_2)
print("global_list:", global_list)

I feel like it could be optimized. (maybe I didn’t searched enough on the random library) in term of efficicency (I’m working on millions of elements) and in terms of density (I would prefer to have 1 or 2 lines of code for the function).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How about:

def get_2_random_list(global_list, repartition):
    g_list = list(global_list)
    random.shuffle(g_list)
    split_point = round(len(g_list)*repartition)
    
    return g_list[:split_point], g_list[split_point:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading