How to find the index of the element in a list that first appears in another given list?

2024/11/17 5:09:23
a = [3, 4, 2, 1, 7, 6, 5]
b = [4, 6]

The answer should be 1. Because in a, 4 appears first in list b, and it's index is 1.

The question is that is there any fast code in python to achieve this?

PS: Actually a is a random permutation and b is a subset of a, but it's represented as a list.

Answer

If b is to be seen as a subset (order doesn't matter, all values are present in a), then use min() with a map():

min(map(a.index, b))

This returns the lowest index. This is a O(NK) solution (where N is the length of a, K that of b), but all looping is executed in C code.

Another option is to convert a to a set and use next() on a loop over enumerate():

bset = set(b)
next(i for i, v in enumerate(a) if v in bset)

This is a O(N) solution, but has higher constant cost (Python bytecode to execute). It heavily depends on the sizes of a and b which one is going to be faster.

For the small input example in the question, min(map(...)) wins:

In [86]: a = [3, 4, 2, 1, 7, 6, 5]...: b = [4, 6]...:In [87]: %timeit min(map(a.index, b))...:
608 ns ± 64.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)In [88]: bset = set(b)...:In [89]: %timeit next(i for i, v in enumerate(a) if v in bset)...:
717 ns ± 30.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
https://en.xdnf.cn/q/120214.html

Related Q&A

How to yield fragment URLs in scrapy using Selenium?

from my poor knowledge about webscraping Ive come about to find a very complex issue for me, that I will try to explain the best I can (hence Im opened to suggestions or edits in my post).I started usi…

Django Database Migration

Hi have a django project a full project now I want to migrate to mysql from the default Sqlite3 which is the default database. I am on a Mac OS and I dont know how to achieve this process. Any one wit…

Search engine using python for bookmarked sites [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 1…

How to extract only particular set of structs from a file between braces in python

a. Have a scenario, where in my function reads in a file which contains list of c-structures as shown below, reads the file and extracts all the information between { } braces for each structure and st…

Selection of Face of a STL by Face Normal value Threshold

I want to write a script in Python which can generate facegroups in a STL as per the Face Normal value condition. For example, Provided is the snap of Stl, Different colour signifies the face group con…

Python , Changing a font size of a string variable

I have a variable that gets sent to a email as text but the text is all pretty much a standard size with everything the same. I would like to add some emphasis to it as well as make it bigger and make …

Python http.server command gives Syntax Error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

If statement to check if the value of a variable is in a JSON file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Assign variables to a pandas dataframe when specific cell is empty

I am assigning some variables to values from a data frame. The data frame created using this code data = [[tom, 10], ["", 15], [juli, 14]] df = pd.DataFrame(data, columns=[Name, Age])So after…

Try Except for one variable in multiple variables

I am reading every row in a dataframe and assigning its values in each column to the variables The dataframe created using this code data = [[tom, 10], [, 15], [juli, 14]] df = pd.DataFrame(data, colum…