1

This is probably a beginners question but I don't know how to search for an answer (because I cannot "name" the question)

I have 2 lists or a tuple of 2 lists

xxx = ["time1", "time2", "time3"]
yyy = ["value1", "value2", "value3"]
zzz=(xxx,yyy)

now I would like to create a list/tuple for every entry result should be

[['time1', 'value1'], ['time2', 'value2'], ['time3', 'value3']]

I'm able to do this with a for loop (and zip) but is there no "nicer" solution? Here is a similar question but I'm not able to use the resolution given there for my probelms

Community
  • 1
  • 1
nobs
  • 708
  • 6
  • 25

2 Answers2

11

Use the builtin zip function:

 zzz = zip(xxx, yyy) 

Of course, this creates a list of tuples (or an iterable of tuples in python3.x). If you really want a list of lists:

 #list (python2.x) or iterable(python3.x) of lists
 zzz = map(list,zip(xxx,yyy)) 

or

 #list of lists, not list of tuples
 #python 2.x and python 3.x
 zzz = [ list(x) for x in zip(xxx,yyy) ]

If you're using python3.x and you want to make sure that zzz is a list, the list comprehsion solution will work, or you can construct a list from the iterable that zip produces:

#list of tuples in python3.x.  
zzz = list(zip(xxx,yyy)) #equivalent to zip(xxx,yyy) in python2.x
                         #will work in python2.x, but will make an extra copy.
                         # which will be available for garbage collection
                         # immediately
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • thanks for the quick answer it should work in python 2.7 and 3.x so I have to use a "generic" approach – nobs Sep 06 '12 at 14:18
  • 1
    `list(zip(...))` fits the bill, assuming you don't mind an unnecessary copy in 2.7. – Karl Knechtel Sep 06 '12 at 14:19
  • 2
    @nobs -- One of the above solutions should work for you. If you want a list of lists and not a list of tuples, the list comprehension is probably your best bet. If a list of tuples is OK, then `list(zip(...))` will work in both cases. – mgilson Sep 06 '12 at 14:24
0

I notice that your data includes time stamps and numbers. If you're doing number-intensive calculations, then numpy arrays might be worth a look. They offer better performance, and transposing is very simple. ( arrayname.transpose() or even arrayname.T )

abought
  • 2,652
  • 1
  • 18
  • 13
  • you are right but this is the response i get from a c-dll call and I have to change the data in something more "manageable" also its only some test function, so speed is currently no topic (but I'm using python to test the speed of the CDLL :-) ) – nobs Sep 06 '12 at 20:43