A couple things:
- Try
enumerate
- Instead of
darr
being a list
, use a dict
and store the dvp
values as keys, with the xindex
and pindex
variables as values
Here's the code
for xindex, xvalue in enumerate(xarr):
darr = {}
for pindex, pvalue in enumerate(parr):
dvp = math.fabs(xvalue - pvalue)
darr[dvp] = {'xindex': xindex, 'pindex': pindex}
mini = min(darr.keys())
minix = darr[mini]['xindex']
minip = darr[mini]['pindex']
minindex = darr.keys().index(mini)
print "minimum_index> {0}, is the difference of xarr[{1}] and parr[{2}]".format(minindex, minix, minip)
darr.clear()
Explanation
The enumerate
function allows you to iterate over a list and also receive the index of the item. It is an alternative to your range(100)
. Notice that I don't have the line where I get the value at index xpre
, ppre
, this is because the enumerate
function gives me both index and value as a tuple.
The most important change, however, is that instead of your darr
being a list like this:
[130, 18, 42, 37 ...]
It is now a dictionary like this:
{
130: {'xindex': 1, 'pindex': 4},
18: {'xindex': 1, 'pindex': 6},
43: {'xindex': 1, 'pindex': 9},
...
}
So now, instead of just storing the dvp
values alone, I am also storing the indices into x
and p
which generated those dvp
values. Now, if I want to know something, say, Which x
and p
values produce the dvp
value of 43? I would do this:
xindex = darr[43]['xindex']
pindex = darr[43]['pindex']
x = xarr[xindex]
p = parr[pindex]
Now x
and p
are the values in question.
Note I personally would store the values which produced a particular dvp
, and not the indices of those values. But you asked for the indices so I gave you that answer. I'm going to assume that you have a reason for wanting to handle indices like this, but in Python generally you do not find yourself handling indices in this way when you are programming in Pythonic manner. This is a very C way of doing things.