jo_
jo_

Reputation: 731

How to find indices of first two elements in a list that are any of the elements in another list?

How do I find the indices of the first two elements in a list that are any of the elements in another list?

For example:

story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
elementsToCheck = ['a', 'c', 'f', 'h']

In this case, the desired output is a list indices = [0,2] for strings 'a' and 'c'.

Upvotes: 9

Views: 1650

Answers (5)

kendfss
kendfss

Reputation: 514

Here's a slightly more general approach

def firstShared(story,elementsToCheck,n=2):
    overlap = set(i for i in elementsToCheck if i in story)
    firstn = sorted(overlap,key=elementsToCheck.index)[:n]
    indices = [story.index(i) for i in firstn]
    return(indices)
    
    
if __name__ == '__main__':
    n = 2
    story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
    elementsToCheck = ['a', 'c', 'f', 'h']
    # elementsToCheck = ['a', 'b', 'c', 'd', 'f', 'h']
    for i in range(4):
        print(firstShared(story,elementsToCheck,i))
    # []
    # [0]
    # [0, 2]
    # [0, 2]

Upvotes: 1

Gil Pinsky
Gil Pinsky

Reputation: 2493

Possibly the shortest way to implement this:

[i for i, x in enumerate(story) if x in elementsToCheck][:2]

Upvotes: 3

AlexNe
AlexNe

Reputation: 959

Here’s more of a pythonic solution. I guess each element you want to check should be unique, so it’s better to use a set instead of a list. You can look up the indices of each element you want to check and return the two smallest ones.

story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
elementsToCheck = {'a', 'c', 'f', 'h', 'd'}

idxs = {story.index(x) for x in elementsToCheck if x in story}

print(
    min(idxs), min(idxs-{min(idxs)})
)

Upvotes: 1

Bhautik Domadiya
Bhautik Domadiya

Reputation: 100

story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
elementsToCheck = ['a', 'c', 'f', 'h']
tmp=[]
for i in range(0,len(elementsToCheck)):
    if elementsToCheck[i] in story and i<2:
        tmp.append(story.index(elementsToCheck[i]))
print(tmp)

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195418

story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
elementsToCheck = ['a', 'c', 'f', 'h']

out = []
for i, v in enumerate(story):
    if v in elementsToCheck:
        out.append(i)
    if len(out) == 2:
        break

print(out)

Prints:

[0, 2]

Upvotes: 7

Related Questions