Appending to list of lists randomly [duplicate]
Appending to list of lists randomly [duplicate]
This question already has an answer here:
I have an initial list, comprising 1000 lists, some empty and some not. I'm trying to disperse 2000 floats amongst those empty lists at random(empty_list45, empty_list2, ..., empty_randn), not in order (empty_list1, empty_list1, ..., empty_listn).
Here's my attempt:
#the list containing lists.
folder = [] * 1000
for i in range(len(newOPsys_i)):
folder[newOPsys_i[i]] = (newOP[i])
#list of indices of empty lists in folder, where folder is the list comprising 1000 lists that may or may not be empty
empty =
for i in range(len(folder)):
if not folder[i]:
empty.append(i)
#function that pulls a random index from any called list
def rand(mylist):
rando = random.randint(0,len(mylist)-1)
return(rando)
#my attempt at appending 2000 floats to random empty lists in folder
for i in range(0,2000):
x = empty[rand(empty)]
print(folder[x])
folder[x].append(match[x][random.randint(0,len(match[x])-1)]) #match is a separate list where I wish to pull the floats from, and place them into the empty lists.
My output looks something like:
[3.9]
[3.9, 7.8]
[3.9, 7.8, 54.9]
From the print, what seems to be happening instead is that in the first iteration an empty list is found then a single float is appended. On the next iteration, another empty list is randomly found, but appended to this empty list is the float from the last iteration, along with a new float. This is not what I want to happen, I just want those single random floats appended each iteration. Any insights?
Thanks in advance.
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
@sauravverma no, I want to disperse the 2000 floats amongst randomly chosen empty lists.
– Sayre
Sep 1 at 19:51
1 Answer
1
import random
f = [[1, 2, 3], [6, 7, 8], [10, 67, 89], [34, 54, 32, 76], [24, 90, 9, 4, 2]]
for _float in <2000 floats>:
integer = random.randint(0, len(f)-1) #this will shuffle your list of lists
f[integer].append(_float)
Since you are shuffling your list, the last list will be random and you can append your float to the last list or any other index for that matter.
OUCH. You are shuffling 1000 inner lists 2000 times to put 1 float in it? Why not use a
random.randint(0,999) to simply randomize which list to use and then allLists[randomIndex].append(_one_float_) that would be a couple thousand times more effective– Patrick Artner
Sep 1 at 20:00
random.randint(0,999)
allLists[randomIndex].append(_one_float_)
You want to append your 2000 floats at random to a list chosen randomly?
– GraphicalDot
Sep 1 at 19:49