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)
        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).

>Solution :

How about:

def get_2_random_list(global_list, repartition):
    g_list = list(global_list)
    split_point = round(len(g_list)*repartition)
    return g_list[:split_point], g_list[split_point:]

Leave a ReplyCancel reply