开发者

How to access the specific locations of an integer list in Python?

I have an integer list which should be used as indices of another list to retrieve a value. Lets say we have following array

    a = [1,2,3,4,5,6,7,8,9]

We can get the specific elements using following code

    import operator
    operator.itemgetter(1,2,3)(a)

It will return the 2nd, 3rd and 4th item.

Lets say i have another list

    b=[1,2,3]

But if I try to run the following code it开发者_如何学Python gets an error

    operator.itemgetter(b)(a)

I am wondering if someone could help me please. I think its just the problem that I have to convert the b to comma seprated indices butnot very sure.

Thanks a lot


Use *:

operator.itemgetter(*b)(a)

The * in a function call means, unpack this value, and use its elements as the arguments to the function.


Since you have tagged your question with the numpy tag, you could also consider making a an array so this works:

from numpy import array
a = array([1,2,3,4,5,6,7,8,9])
b = [1,2,3]
a[b]


The first argument to itemgetter needs to be a tuple. You can do this with:

apply(operator.itemgetter, tuple(b))(a)

There might be a cleaner/more idomatic way of doing this, but this does work for your example.


You can also try:

map(a.__getitem__, b)

The code returns a list in Python 2 or an iterator in Python 3. If you need to convert it to tuple, just put it in a tuple().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜