-3

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.

key
  • 63
  • 3
  • 9

1 Answers1

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