Reputation: 135
Title is a bit vague, here's my problem.
I'm trying to reduce the contents of one list based on the values to the right and left of the item in the other list.
An example:
If I have the following 2 lists.
a = [1,2,3,5,7,8]
b = [1,2,3,4,7]
and my constraint is a = b+1
I want to return
a = [2,3,5,8]
b = [1,2,4,7]
1 and 7 can't be in a because there is no 0 or 6 in b.
3 cant be in b because there is no 4 in a.
I'm having problems conceptualizing how I should even approach this.
My current attempt is:
c = []
d = []
for i in a:
for j in b:
if (i+1) == j or (i-1) ==j:
c.append(i)
d.append(j)
with the idea that I will then make a = c and b = d but the result i get is
c= [1,2,2,3,3,5,8]
d= [2,1,3,2,4,4,7]
I totally understand why I get those numbers in c and d but im afraid the logic of how to approach getting the right numbers totally escapes me. This is a small subset of a larger project I have to do but am getting caught up with this part in particular. Any help would be appreciated.
Upvotes: 0
Views: 56
Reputation: 4250
One simple and maybe inefficient answer (edited with list comprehension):
c = [el for el in a if (el-1) in b]
d = [el for el in b if (el+1) in a]
Upvotes: 1