1

Very beginner question but it is driving me mad. sample1, sample2 etc. are Pygame.mixer.sound objects.

sample_list = []
sample_list.append(sample1)
sample_list.append(sample2)
sample_list.append(sample3)

Is fine, but I want to do that using a for style loop, e.g.

for j in range(1, 3, 1):
    sample_list.append(sample + j)

But that is trying to add a number to a sound object so isn't right. I can add the equivalent string by;

for j in range(1, 3, 1):
    sample_list.append("sample" + str(j))

But that doesn't refer to the objects I want, just adds those strings. I've tried must permutations of syntax I can think of but it is still alluding me! Thanks.

4

4 回答 4

3

Don't store the objects in variables in the first place; store them directly into a list, and then you will be able to index them by integer.

If the integer identifiers are sparse, use a dict indexed by integer.

于 2012-11-17T20:50:04.290 回答
2

I would recommend storing these in a dict to begin with. It is almost the same effect for you to reference by a name, but without the explicit object symbol for each:

samples = {
    "sample1": Sample(),
    "sample2": Sample()
}
samples['sample3'] = Sample()

This is the preferred approach when you have a dynamic number of objects you are creating and want to be able to grab them by a name later. You can store 100's of these in your dict without cluttering up your namespace.

And later if you are trying to apply this to your loop, you can reference the string names:

for i in xrange(1,4):
    sample_list.append(samples["sample" + str(i)])

As a side note another way to get attributes by name when they live on some object is to use getattr. Assume you have this:

class Sampler(object):
    pass

sampler = Sampler()
sampler.sample1 = Sample()
sampler.sample2 = Sample()
sampler.sample3 = Sample()

You can then reference by name via: getattr(sampler, "sample1")

Note: As mentioned in comments by @Marcin, if you don't care about having a string identifier to be able to look up your items, and they are just purely sequential by number, you can use this same approach but with a list. It depends on your needs.

It is possible you might want to end up doing something like:

samples = {
    "bang1": Sample(),
    "bang2": Sample(),
    "bang3": Sample(),
    "shot1": Sample(),
    "shot2": Sample(),
    ...
}

... Which would then allow you to look up sequential subsets of those sounds.

于 2012-11-17T20:51:32.173 回答
0

You can dynamically load variables from the locals() mapping:

for j in range(1, 4):
    sample_list.append(locals()["sample" + str(j)])

Generally, you want to avoid such tricks; find other ways to store your sample variables, in a mapping or a list for example.

于 2012-11-17T20:46:50.900 回答
-2

Looks like the wrong approach, but nevertheless.

sample_list = [eval('sample' + str(i)) for i in range(1, 4)]
于 2012-11-17T21:22:20.537 回答