0

I have a list of n strings. For example, strings = ('path1','path2',path3')

I want to create n variables that are equal to functions on these strings. For example:

s1=pygame.mixer.Sound('path1')
s2=pygame.mixer.Sound('path2')
s3=pygame.mixer.Sound('path3')`

I've looked this up a few times before and answers always seem to refer to dictionaries. I am not too familiar with dictionaries although I know their basic function. I don't know how I would use a dictionary to accomplish this.

3 Answers 3

2

The problem with dynamically creating variables is: how do you plan on referring them in your code? You'll need to have some abstracted mechanism for dealing with 0..n objects, so you might as well store them in a data type that can deal with collections. How you store them depends on what you want to do with them. The two most obvious choices are list and dict.

Generally, you'll use a list if you want to deal with them sequentially:

paths = ['path1', 'path2', 'path3']
sounds = [ pygame.mixer.Sound(path) for path in paths ]

# play all sounds sequentially
for sound in sounds:
    sound.play()

Whereas dict is used if you have some identifier you want to use to refer to the items:

paths = ['path1', 'path2', 'path3']
sounds = { path: pygame.mixer.Sound(path) for path in paths }

# play a specific sound
sounds[name].play()
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use a dictionary. Use map.

s = map(pygame.mixer.Sound, strings)

The above statement will call pygame.mixer.Sound with each of the strings in strings as arguments, and return the results as a list. Then you can access the variables like you would access any item from a list.

s1 = s[0] # based on your previous definition

Comments

1

The idea is you use a dictionary (or a list) instead of doing that. The simplest way is with a list:

sounds = [pygame.mixer.Sound(path) for path in strings]

You then access them as sounds[0], sounds[1], sounds[2], etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.