x= [0,2,3,5,6];
y= [64,384,1024,4096,384];
开发者_Go百科
The above are two arrays I'm using. Im trying to match the elements together in a pythonic way
example:
if xType
is 2 i want to compute a variable called yType
to correspond to its value(position wise) in y. so i should get y = 384
. if xType = 3
i should get 1024.
How would i go about doing this
If your specific aim is to generate a dict
from the two lists you've given, use zip
:
>>> x = [0,2,3,5,6]
>>> y = [64,384,1024,4096,384]
>>> dict(zip(x, y))
{0: 64, 2: 384, 3: 1024, 5: 4096, 6: 384}
And get rid of those semicolons!
If you don't need a mapping type, but just want to create pairs of items, zip
alone will do:
>>> zip(x, y)
[(0, 64), (2, 384), (3, 1024), (5, 4096), (6, 384)]
This is so short, even Stack Overflow did not allow me to submit such a short answer:
y[x.index(2)]
This will return element from y
corresponding to the position of 2
or any other given value from within x
list.
Hope it helped :)
Ps. Indeed dictionaries may be something you need. Try using them.
If the elements in x
are unique, you can use them as the keys in a dict to lookup the elements in y
that have the same index. Like this:
x = [0,2,3,5,6]
y = [64,384,1024,4096,384]
y_from_x = dict(zip(x,y))
print y_from_x[2] # prints 384
print y_from_x[3] # prints 1024
This is useful if you want to do lots of lookups, but if you want to do just one lookup Tadeck's answer is more efficient
a = {0: 64, 2:384, ...}
look up 'maps in python' or something like that
>>> xymap = dict(zip(x, y))
>>> xymap[2]
384
However, if you also need to lookup elements in x for y, you'll need a yxmap
as well. And if you need these to be lists for some reason (perhaps because you're modifying them during the course of your program), you could use i = x.index(2)
and then y[i]
.
精彩评论