I'm trying to split all nested lists to separate lists. For example:
all_v_100_history = [[2,4],[2,1,5],[6,3,5]]
, and I want to separate to individual sublists:
l1=[2,4]
,
l2=[2,1,5]
,
l3=[6,3,5]
...
The number of nested lists is j
, so my goal is to separate all_v_100_history
to j
number of sublists.
Asked
Active
Viewed 238 times
-3

key
- 63
- 3
- 9
-
1Why do you want to separate when you can get it with `all_v_100_history[n]` notation. – Mohammad Yusuf Feb 16 '17 at 02:17
-
2Why on God's green Earth would you want to do this? – TigerhawkT3 Feb 16 '17 at 02:20
-
What’s the difference between this and just copying the list? Or using the old list? – rassar Feb 16 '17 at 11:55
1 Answers
0
this is an odd question, and you probably should NOT do this, but here goes:
lcls = locals()
for i in range(len(all_v_100_history)):
lcls['l' + str(i)] = all_v_100_history[i]
the "magic" part here is locals()
which gives you the local variable hash table, letting you access keys dynamically, you dont even have to predeclare the variables to assign them. at the end you will end with a bunch of l1,l2...lj variables in the local context
the above will NOT work inside a function, but there is a hack for that which im adding for the sake of completeness (its bad coding don't use this)
def my_func(all_v_100_history):
lcls = locals()
for i in range(len(all_v_100_history)):
lcls['l' + str(i)] = all_v_100_history[i]
return #return whatever it is you want to return
exec "" #this is the magic part
this only works in python 2.

Nullman
- 4,179
- 2
- 14
- 30
-
1
-
1It also does not work **at all** ... put this inside a function and then try to `print(l1)` ... – donkopotamus Feb 16 '17 at 02:21
-