开发者

Naming a new list from another list in Python

this may sound like a strange question from a Python noob, but here's the deal. I have a list with a bunch of (string) entries. I want to take one of those entries, add another string to the end of it, and then create a new array with that name. Eg, I have

list=["foo","bar"]

and I want to get something to the effect of

fooblah = []

I've been trying to do it this way

list[0] + "blah" = []

Obviously this doesn't work because the first part is a string instead of a variable name, but I'm not sure how to fix it. From what I've read of other people's problems, the solution might be in using a dictionary instead (?), bu开发者_JAVA技巧t to be honest I'm not really sure how dictionaries work yet.

Thanks, J.


I would use a python dictionary they can use practically anything as an index instead of integers. You're code could get messy and unreadable really fast if you are dynamically creating local / global variables.

For example

l = ["foo","bar"]
d = {}
d[l[0] + "blah"] = []
d[l[0] + "blah"].append("foo")

Using a dictionary will give you some other neat advantages, for example, you can loop through all of the new lists you create.

for k,v in d.iteritems():
    print "{0} --> {1}".format(k,v)


Well, if you really want to do this one way would be through the globals() or locals() methods which return a dictionary of the current symbols:

globals()[list[0] + 'blah'] = [  ]

Note that list is the name of a built-in type, so using it as your variable name is considered bad practice.

Also, this is a highly unusual need; what exactly are you trying to accomplish? Perhaps there is a better way?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜