Create New Lists From Elements Of A List
Is there a way to create multiple lists with names from elements of another list. Eg: names=['Rob','Mark','Steve'] Is there a way to create lists like: Rob=[] Mark=[] Steve=[]
Solution 1:
The one obvious way is like this:
>>> names = ["Rob","Mark","Steve"]
>>> lists = {name: [] for name in names}
>>> print lists
{'Steve': [], 'Rob': [], 'Mark': []}
Solution 2:
You can use the exec statement with a string as argument. It will parse the string as a suite of Python statements.
names=["Rob","Mark","Steve"]
S = "".join([n +'= [];'for n in names])
exec(S)
In [1]: print Rob, Mark, Steve
[] [] []
Post a Comment for "Create New Lists From Elements Of A List"