简体   繁体   English

将 function 应用于列表中的每个项目

[英]Apply a function to every item in a list

I have the following code for pygame but it applies generally to python我有 pygame 的以下代码,但它通常适用于 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循环中的 i 是 integer 并且 mixer.set_Volume 是元素的有效操作

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:编写时,您正在迭代expl_sounds中的元素,因此您可以这样做:

for i in expl_sounds:
     i.set_volume(Sound_Volume)

Your error comes from your misunderstanding of the syntax for i in expl_sounds .您的错误来自您对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循环中的 i 是 integer不正确, iexpl_sounds的一个元素,是您之前添加的pygame.mixer.Sound实例


So use the object directly所以直接使用object

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. “for i in expl_sounds”中的“i”是声音 object 本身,而不是数组索引。

Try the following:尝试以下操作:

for i in expl_sounds:
     i.set_volume(Sound_Volume)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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