Question : Numpy *zip with units

Hi,

I have the attached code. However, after zipping back up i and t, the units are no longer 'attached' to t.
Is there away to zip up with the units as well, i've tried zip(i, t*second) although this doesn't work.

Any suggestions?
Cheers,
James
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
x = [(1, 0.4 ms), (4, 0.6 ms), (7, 1.0 ms)]
 
i,t=zip(*x)
 
# do stuff to i and t
 
x2 = zip(i,t)
Open in New Window Select All

Answer : Numpy *zip with units

Well, the doc says:

  zip([iterable, ...])
    This function returns a list of tuples, where the i-th tuple contains the i-th element
    from each of the argument sequences or iterables. The returned list is truncated
    in length to the length of the shortest argument sequence.

Try the modified snippet below to understand the zip(). The second argument was converted to strings to show the wanted value. The same way it could be the instance of another class that show itself in the form of readable string. The example below produces:

C:\tmp\___python\James_h1023>a.py
[(1, '0.4 ms'), (4, '0.6 ms'), (7, '1.0 ms')]
(1, 4, 7)
('0.4 ms', '0.6 ms', '1.0 ms')
[(1, 4, 7), ('0.4 ms', '0.6 ms', '1.0 ms')]
[(1, '0.4 ms'), (4, '0.6 ms'), (7, '1.0 ms')]

The first line is the original list. The zip(*x) -- better the *form of passing the argument -- means that the x is expected to have form of a list the elements of which are extracted and used as real arguments. This way, it is the same as if you used

i,t = zip((1, '0.4 ms'), (4, '0.6 ms'), (7, '1.0 ms'))
print i
print t

In other words, zip() has 3 iterable inputs and returns the list of tuples where the first tuple contains the first elements of the input tuples -- i.e. (1, 4, 7) -- and the second tuple contains the second elements... (and there are no more elements in the input sequences).

The multiple assignment takes the first tuple and names it 'i' and the second tuple and names it 't' -- as shown on the next lines of the input.

If you decided not to use the multiple (a.k.a. parallel) assignment, you would get the list like the one on the fourth line.

When you zip(i,t), you must get the original. Similarly, you could also do

x3 = zip(*lst)
print x3

(try to add this to the sample)

Again, it does not matter what is the second argument of the original input tuples. The zip() does not change the terminal values. It only reorganizes the structure of references to the terminal objects.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
x = [(1, '0.4 ms'), (4, '0.6 ms'), (7, '1.0 ms')]
print x
 
i,t = zip(*x)
print i
print t
 
lst = zip(*x)
print lst
 
x2 = zip(i,t)
print x2
Open in New Window Select All
Random Solutions  
 
programming4us programming4us