On 07/16/2013 09:48 PM, Jim Mooney wrote:
This is puzzling me. I have a folder with about 125 movie sound clips,
like "I'll be back," blues brothers theme, oompa-loompas, etc. I play
seven random ones on windows startup, which works fine. But just so I
don't repeat a clip, I delete it from the dictionary on each go-round.
However, to make sure that happened, I printed the key-length on each
go-round.  It should be shorter by one every time but I always get a
length of 125. (Yes, I know there are about five different ways to do
this, but I thought I'd try a dictionary ;')

Also, the printout doesn't occur until after all the sounds play, so
maybe that has something to do with it. But I also tried saving the
lengths in a list while the program ran, and got the same result. A
list of all '125'

#Using Python 2.7 on Win 7

import winsound
import random, os
random.seed()

lenlist = []
file_list = os.listdir('WAV')

for clip in range(0,7):
     file_dict = dict(enumerate(file_list))
     sound_key = random.choice(range(0,len(file_list)))
     winsound.PlaySound('WAV/' + file_dict[sound_key], winsound.SND_FILENAME)
     del file_dict[sound_key]

You're deleting something from a dictionary that you're going to recreate next time through the loop. If you really want to delete it, remove it from the file_list. Your dictionary is accomplishing precisely nothing anyway, since file_dict[key] will give you the same value as file_list[key].

But if you like the dictionary, then create it outside the loop. Now deleting things from it will actually mean something. Of course, then your random.choice() will have to be over the dictionary, not over the list. Or you'll have to handle the case where it happens to choose the same item again, with a loop inside the loop to handle those retries...


     print(len(file_dict.keys()))

Seems to me the obvious choice is just to use random.choice of the enumerated file list, then delete the item from the list. Way too much indirection in the code above.


--
DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to