I appreciate this may not be directly possible so I would be interested how you would go about solving this problem for a general case.
I have a list item that looks like this, [(array,time),(array,time)...]
the array is a numpy array which can have any n by m dimensions. This will look like array[[derivatives dimension1],[derivatives dimension 2] ...]
From the list I want a function to create two lists which would contain all the values at the position passed to it. These could then be used for plotting. I can think of ways to do this with alternative data structures but unfortunately this is no an option.
Essentially what I want is
def f(list, pos1, pos2):
xs = []
ys = []
for i in list:
ys.append(i pos1)
xs.append(i pos2)
return xs, ys
Where i pos1
is开发者_如何学编程 equivalent to i[n][m]
The real problem being when it's 1 by 1 so i can't just pass integers.
Any advice would be great, sorry the post is a bit long I wanted to be clear.
Thanks
If I'm understanding your question correctly, you essentially want to select indexes from a list of lists, and create new lists from that selection.
Selecting indexes from a list of lists is fairly simple, particularly if you have a fixed number of selections:
parts = [(item[pos1], item[pos2]) for item in list]
Creating new lists from those selections is also fairly easy, using the built-in zip() function:
separated = zip(*parts)
You can further reduce memory usage by using a generator expression instead of a list comprehension in the final function:
def f( list, pos1, pos2 ):
partsgen = ((item[pos1], item[pos2]) for item in list)
return zip(*partsgen)
Here's how it looks in action:
>>> f( [['ignore', 'a', 1], ['ignore', 'b', 2],['ignore', 'c', 3]], 1, 2 )
[('a', 'b', 'c'), (1, 2, 3)]
Update: After re-reading the question and comments, I'm realizing this is a bit over-simplified. However, the general idea should still work when you exchange pos1 and pos2 for appropriate indexing into the contained array.
if i understand your question, something like the following should be easy and fast, particularly if you need to do this multiple times:
z = np.dstack([ arr for arr, time in lst ])
x, y = z[pos1], z[pos2]
for example:
In [42]: a = arange(9).reshape(3,3)
In [43]: z = np.dstack([a, a*2, a*3])
In [44]: z[0,0]
Out[44]: array([0, 0, 0])
In [45]: z[1,1]
Out[45]: array([ 4, 8, 12])
In [46]: z[0,1]
Out[46]: array([1, 2, 3])
精彩评论