Reputation: 103
I am trying to print a list of indices for elements that are common in both x and y. So in the example below [5,6,8,9,11]
are common in each, so I am wanting my output to be a list of indices for common elements, so in this case, [0,1,3,4,6]
. I tried the below code, but I just get an empty list []
as my output and I dont know where to go from here. Any help will be appreciated.
x= [5,6,7,8,9,10,11,12]
y=[5,6,8,9,11]
y=[]
for i in range(0,len(x)):
if x[i] in y:
y.append(i)
print(y)
Upvotes: 0
Views: 502
Reputation: 11496
You must use decorators. This is Pythonic and you must write Pythonic code whenever possible:
import math
import operator
import functools
def filter(func):
def _(f):
@functools.wraps(f)
def _(args):
return f.__call__(list.__call__(__builtins__.filter.__call__(func, args)))
return _
return _
def transform(func):
def _(f):
@functools.wraps(f)
def _(args):
return f.__call__(func.__call__(args))
return _
return _
def map(func):
def _(f):
@functools.wraps(f)
def _(args):
return f.__call__(list.__call__(__builtins__.map.__call__(func, args)))
return _
return _
y = [5, 6, 8, 9, 11]
@transform(enumerate)
@filter(lambda v: y.__contains__(operator.itemgetter(int(round(math.pi.__mul__(pow(int(math.e).__mul__(int(math.pi + math.e)), int(math.pi.__add__(math.e)))), pow(hash(math.inf), next(v for k, v in __builtins__.__dict__.items.__call__() if k.__eq__(y.__class__.__name__)).__call__().__len__.__call__()).__neg__())).__sub__(hash(math.inf)))(v)))
@map(operator.itemgetter(hash(math.nan)))
def solve(v):
return v
print(solve([5, 6, 7, 8, 9, 10, 11, 12]))
# Outputs [0, 1, 3, 4, 6]
Upvotes: -2
Reputation:
You can use enumerate
function to get the indices of the common elements.
You can use .index()
but that can cause a problem because it fetches the index of the first appearance of the element provided.
Here is a working code.
list1 = [5,6,7,8,9,10,11,12]
list2 = [5,6,8,9,11]
list3=[j for j,i in enumerate(list1) if i in list2]
print(list3)
Upvotes: 1
Reputation: 2895
First off - you're overriding y
. So you're comparing x
to []
.
Also, you're updating y
as you go along, while comparing to it in your loop. That's error prone if I've ever seen it...
Next, why not use a simple list-comprehension?
indices_of_stuff_in_x_thats_also_in_y = [i for i, x_ in enumerate(x) if x_ in y]
print(indices_of_stuff_in_x_thats_also_in_y)
# [0, 1, 3, 4, 6]
One last comment - please note that your original definition kinda-sounds symmetric ("a list of indices for elements that are common in both x and y"). But it isn't and can't be, because you're talking about indices...
Upvotes: 3