问题描述:

I want to make a list and call it a name which I only know after I run the program:

For example:

#making shelfs

group_number = 1

group_name = 'group' + str(group_number)

print group_name

group_name will be: group1

Now I want to make an empty list called group1. How to do such a thing?

网友答案:

Usually you just put this into a dictionary:

d = {group_name:[]}

Now you have access to your list via the dictionary. e.g.:

d['group1'].append('Hello World!')

The alternative is to modify the result of the globals() function (which is a dictionary). This is definitely bad practice and should be avoided, but I include it here as it's always nice to know more about the tool you're working with:

globals()[group_name] = []
group1.append("Hello World!")
网友答案:

You are wanting to create a pseudo-namespace of variables starting with "group". Why not use a dict instead?

#making shelfs
groups = {}
group_number = 1
name = str(group_number)
groups[name] = [] # or whatever
print groups[name]

This is subtly different to @mgilson's answer because I am trying to encourage you to create new namespaces for each collection of related objects.

网友答案:

you do this:

locals()['my_variable_name'] = _whatever_you_wish_

or

globals()['my_variable_name'] = _whatever_you_wish_

or

vars()['my_variable_name'] = _whatever_you_wish_

Google to find out the differences yourself :P

相关阅读:
Top