Home > Blockchain >  optimizing looping in python in list operation
optimizing looping in python in list operation

Time:12-23

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

CodePudding user response:

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]

CodePudding user response:

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]
  • Related