How to randomly assign elements of a list into 3 arrays?
Anonymous in /c/coding_help
475
report
I have a 9-element list of strings, and I want to randomly assign 3 strings into each of 3 arrays, and do this for a specified number of times (e.g. 1000). Then I want to read and write from arrays 0 and 1, and write to array 2 exclusively.<br><br>So I want to do something like this:<br><br>```<br>array0 = [str1, str2, str3]<br>array1 = [str4, str5, str6]<br>array2 = [str7, str8, str9]<br>```<br><br>But randomly re-arrange the strings and do it 1000x. I can definitely do this with a brute-force method, but I want to do this in the most Pythonic way possible. (And more importantly, Pythonic way as in most efficient way, even if it means using a different data type)<br><br>I have this as my brute force method so far:<br><br>```python<br>import random<br>array0 = []<br>array1 = []<br>array2 = []<br><br>num_times = 1000<br>num_times_counter = 0<br>while num_times_counter < num_times:<br> array0 = []<br> array1 = []<br> array2 = []<br> str_list = ['a','b','c','d','e','f','g','h','i']<br> shuffle_list = str_list[:]<br> shuffle_list = random.sample(str_list, len(shuffle_list))<br> i = 0<br> while i < 3:<br> array0.append(shuffle_list[0])<br> shuffle_list.remove(shuffle_list[0])<br> i += 1<br> i = 0<br> while i < 3:<br> array1.append(shuffle_list[0])<br> shuffle_list.remove(shuffle_list[0])<br> i += 1<br> i = 0<br> while i < 3:<br> array2.append(shuffle_list[0])<br> shuffle_list.remove(shuffle_list[0])<br> i += 1<br><br> ### read from arrays 0, 1 and write to array 2 etc. etc.<br><br> num_times_counter += 1<br>```<br><br>There has to be a better way of doing this. Any suggestions?<br><br>​
Comments (8) 14698 👁️