Reputation: 409
Trying to get something to work where I randomize 4 objects in an array and randomly select one of those. I need to be able to get the original index number for that chosen object back. Any idea on how I should write this as short as possible?
arrayRandomSongs = []
arrayChosen = []
trackChosen = ""
def randomizeArray(self):
del self.arrayRandomSongs[:] # wipes array of all contents without making a new one
self.arrayRandomSongs = self.arraySongs[:]
random.shuffle(self.arrayRandomSongs)
def chooseListing(self):
del self.arrayChosen[:] # same here
for i in xrange(4):
self.arrayChosen.append(self.arrayRandomSongs[i])
del self.arrayRandomSongs[0:3]
def chooseTrack(self):
self.trackChosen = random.choice(self.arrayChosen)
As you can see I would like to select the arayChosen index number for the trackChosen object, but since it's randomized I don't see how I could do that.
Upvotes: 0
Views: 69
Reputation: 1155
You will have to keep track of indexes before randomizing. Then access the index value from the tracking list after randomizing and selecting an element from the randomized list.
For getting index of an element in list you can do <list>.index(<element>)
.
Explanation:
Create a copy of arrayRandomSongs
before shuffling its elements.
original_arrayRandomSongs = arrayRandomSongs[:]
After getting the value of trackChosen
by doing random.choice
, use that value to get its index in original list by doing
original_arrayRandomSongs.index(self.trackChosen)
Upvotes: 2
Reputation: 2698
Well you could do something like this
list = [4,1,3,2]
list_with_indices = [(num,i) for i, num in enumerate(list)]
shuffle(list_with_indices)
essentially you keep track of the original index.
Upvotes: 1