2

I have the following list of lists:

list_sample = [[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.021, 0.021, 0.021, 0.021, 0.021, 0.021, 0.021], [0.022, 0.022, 0.022, 0.022, 0.022, 0.022, 0.022],...]

I'd like to extract each list and attribute it to another list such as:

for i,line in enumerate(list_sample):
    if  i==0:
        Z_level=line
    if i==1:
        XD1=line
    if i==2:
        XD2=line
    .....

Is there a way to make this more efficiently? Thanks

jpcgandre
  • 1,487
  • 5
  • 31
  • 55

4 Answers4

4

Or (complementing RobEarl) answer,

Z_level, XD1, XD2, ... = list_sample

However, if you don't know how big is your list_sample you need to look for how to dynamically set variables in python. You can check some of that here

Community
  • 1
  • 1
pekapa
  • 881
  • 1
  • 11
  • 25
3

If I read you correctly, you want to assign the first sub-list to Z_level, the second to XD1...

Z_level, XD1, XD2 ... = list_sample

If you only want to assign 3 things:

Z_level, XD1, XD2 = list_sample[:3]
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
2

No need for a loop:

Z_level = list_sample[0]
XD1 = list_sample[1]
XD2 = list_sample[2]
...
RobEarl
  • 7,862
  • 6
  • 35
  • 50
2

To infinity, try this ...

for i,line in enumerate(list_sample):
    if i == 0:
        vars()["Z_level"] = line
        continue
    vars()["XD"+str(i)] = line

This is just for fun, but you should probably not use this, read the comments by @defuz and @DSM as to why.

This is probably a better solution :

lists = {}
for i,line in enumerate(list_sample):
    if i == 0:
        lists["Z_level"] = line
        continue
    lists["XD"+str(i)] = line
Emil Davtyan
  • 13,808
  • 5
  • 44
  • 66
  • 1
    I think this is not the case when to use such magic. Create local variables for a large number of similar values ​​is evil. In the end we did not even know how many local variables we have created. – defuz Sep 30 '13 at 15:24
  • @defuz I'm new to python. I'm just playing around. :) – Emil Davtyan Sep 30 '13 at 15:26
  • This won't even work if it's in a function, because modifications to `locals()` aren't guaranteed to be respected. Simply use a standard dictionary instead. – DSM Sep 30 '13 at 15:28
  • @DSM I didn't know that, I'll post a warning. – Emil Davtyan Sep 30 '13 at 15:32