简体   繁体   中英

Apply a function to every item in a list

I have the following code for pygame but it applies generally to python

expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
    expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))

i would like to mute all items in the list individually instead of muting the entire application or mixer. I tried the following:

 for i in expl_sounds:
     expl_sounds[i].set_volume(Sound_Volume)

TypeError: list indices must be integers or slices, not Sound

I dont get the error message. The i in the loop is an integer and the mixer.set_Volume is a valid operation for the elements

What would be the correct way to iterate and apply the volume to each element?

When you write for i in expl_sounds: , you are iterating on the elements in expl_sounds , so you can just do:

for i in expl_sounds:
     i.set_volume(Sound_Volume)

Your error comes from your misunderstanding of the syntax for i in expl_sounds . The i in the loop is an integer isn't true, i is one element of the expl_sounds , a pygame.mixer.Sound instance that you just add before


So use the object directly

for sound in expl_sounds:
    sound.set_volume(Sound_Volume)

To do it by indices, do

for i in range(len(expl_sounds)):
    expl_sounds[i].set_volume(Sound_Volume)

The "i" in "for i in expl_sounds" is the sound object itself, not the array index.

Try the following:

for i in expl_sounds:
     i.set_volume(Sound_Volume)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM