1

I am using the following code for the iteration. but if the length is high, then this will become time-consuming.

a=[11,12,3,4,5,6,15]
b=[1,3,12,15]
c=[1,2,3,4,5,6,7]
d=[]
for i in range(len(a)):
    for j in range(len(b)):
        if b[j]==a[i]:
            d.append(c[i])
print(d)

is there any other optimal way to get this done?

thanks in advance

1
  • Making a dict of b will help considerably. Commented Dec 23, 2021 at 1:05

2 Answers 2

3

Checking if collection contains an object is optimized for sets. You could do:

b_set = set(b)
[ci for ai, ci in zip(a, c) if ai in b_set]
Sign up to request clarification or add additional context in comments.

Comments

2

Use in:

for i,v in enumerate(a):
    if v in b:
        d.append(c[i])

Or a list comprehension:

d = [v for i,v in enumerate(c) if a[i] in b]

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.