Find more than one element index (python)

Asked 2 years ago, Updated 2 years ago, 21 views

For example, I want to find an index with 2,3 in the list l=[1,3,2,4].I tried index ([2,3]) and there is an error. How do I organize an expression? In this case, the answer will be [2,1].

python

2022-09-21 11:39

1 Answers

is the answer by the previous question in the answer. The answers to the above questions are below.

Given an array of indexes, we find an array of elements in the array.

There is no way to start with brackets [] and . So I have to use another method, but I'll tell you two methods. But before that, you should know that Python's index is 0-based. This means that the first element is the 0th element.

Yes)

>>> l = [1, 3, 2, 4]
>>> l[0]
1

1. Use map function

>>> list(map(lambda x: l[x], [1, 2]))
[3, 2]

The map is a built-in function of the Python, which rotates the array to the right to apply the function.

2. Create Array

>>> [l[x] for x in [1, 2]]
[3, 2]

This method is a one-line for statement, which is often used because you can write short codes.

First, the index method is a method that receives integers as parameters. So, similar to the above, you can do the following.

1. Use map function

>>> list(map(l.index, [2, 3]))
[2, 1]

2. Create Array

>>> [l.index(x) for x in [2, 3]]
[2, 1]

I think you can use one of the two main methods.


2022-09-21 11:39

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.