1

I have a list:

letters = ('1', '2', '3', '5', '8', '13', '21')

Having number 8, I can get it's index in letters as: letters.index('8')

No, I have an array which contains only numbers that are in letters.

numbers = [3, 8, 13, 21, 5]

How do I call index (or similar) function on each element?

what I want to get is [2, 4, 5, 6, 3]

Is there such function as index that can grab array instead on single element? If that is required letters can be changed to array

2
  • Python terminology nitpick: letters is a tuple, not a list. numbers is a list, not an array. Commented Dec 8, 2016 at 15:39
  • Will keep that in mind, thanks! Commented Dec 8, 2016 at 16:06

3 Answers 3

3

You can try

letters = ('1', '2', '3', '5', '8', '13', '21')
numbers = [3, 8, 13, 21, 5]

result = [letters.index(str(n)) for n in numbers]

But this works only if all requests are present in letters

You can try this to test if the request in letters

[letters.index(str(n)) if str(n) in letters else -1 for n in numbers]

In case request in not letters, you will have a -1. Beware that -1 is here to indicate that request is not present. letters[-1] returns the last element of the tuple.

Sign up to request clarification or add additional context in comments.

Comments

1

I like to use map functions - this is a great problem to apply a new technique.

def get_index(letters, element):
    return letters.index(str(element))

indices_of_numbers = list(map(get_index, numbers))

we could wrap this in a function so we can remove the letters argument from get_index.

def get_indices_of_numbers(letters, numbers):
    def get_index(element):
        return letters.index(str(element))

    indices_of_numbers = list(map(get_index, numbers))
    return indices_of_numbers

Comments

1

You could convert letters to int array and then use np.searchsorted -

np.asarray(letters,dtype=int).searchsorted(numbers)

Sample run -

In [42]: letters = ('1', '2', '3', '5', '8', '13', '21')

In [43]: numbers = [3, 8, 13, 21, 5]

In [44]: np.asarray(letters,dtype=int).searchsorted(numbers)
Out[44]: array([2, 4, 5, 6, 3])

If letters is such that the int array version is not sorted, we need to feed in the additional argument sorter with searchsorted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.