I need to create 3 lists from my list1. One with 70% of the values and two with 20% and 10%.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# listOutput70 = select 70% of list1 items(randomly)
# with the remaining create two lists of 20% and 10%
#the output can be something like:
#listOutput70 = [2,7,9,8,4,10,3]
#listOutput20 = [1,5]
#listOutput10 = [6]
I already have some code to generate a percentage output, but works only for one list.
import random
def selector():
RandomSelection = []
mySel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
PercentEnter= 70
New_sel_nb = len(mySel)*int(PercentEnter)/100
while len(RandomSelection) < New_sel_nb:
randomNumber = random.randrange(0, len(mySel),1)
RandomSelection.append(mySel[randomNumber])
RandomSelection = list(set(RandomSelection))
print(RandomSelection)
selector()
#[2, 3, 6, 7, 8, 9, 10]
CodePudding user response:
Shuffle the list with random.shuffle()
. Then use slices to get each percentage.
def selector(percents):
RandomSelection = []
mySel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(mySel)
start = 0
for cur in percents:
end = start cur * len(mySel) // 100
RandomSelection.append(mySel[start:end])
start = end
return RandomSelection
print(selector([70, 20, 10]))
CodePudding user response:
Using numpy.split function:
from random import shuffle
from numpy import split as np_split
def selector(og_list, percentages):
if sum(percentages) != 100:
raise ValueError("Percentages must sum to 100!")
percentages.sort()
splits = [round(len(og_list) * percentages[0] / 100),
round(len(og_list) * (percentages[0] percentages[1]) / 100)]
shuffle(og_list)
return [list(subset) for subset in np_split(og_list, splits)]
Usage:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
my_percentages_1 = [10, 20, 70]
my_percentages_2 = [40, 10, 50]
my_percentages_3 = [63, 31, 6]
result_1 = selector(my_list, my_percentages_1)
result_2 = selector(my_list, my_percentages_2)
result_3 = selector(my_list, my_percentages_3)
print(result_1)
print(result_2)
print(result_3)
[[2], [8, 3], [4, 9, 7, 5, 0, 1, 6]]
[[8], [0, 2, 7, 1], [9, 4, 6, 3, 5]]
[[1], [0, 3, 2], [4, 8, 5, 9, 7, 6]]