Reputation: 9
This is my list
my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]
My goal is to sort or create new lists like these
list1 = [18, 19, 20]
list2 = [27, 28, 29]
list3 = [38, 39, 40]
And then compare each of them and only leave items which are equal like that ,
list1 x == list2 x - 10 or list1 x == list3 x - 10
list1 x == list2 x + 10 or list1 x == list3 x + 10
list2 x == list1 x - 10 or list2 x == list3 x - 10
list2 x == list1 x + 10 or list2 x == list2 x + 10
list3 x == list1 x - 10 or list3 x == list2 x - 10
list3 x == list1 x + 10 or list3 x == list2 x + 10
So the final list will be like
final = [18,19,28,29,38,39]
I have wrote those codes but can't achieve the goal. Those were just unsuccessful attempts.
N1
for lst in my_list:
ind = my_list.index(lst)
if int(my_list[ind]) == any(int(x)-10 for x in my_list) or int(my_list[ind]) == any(int(x)+10 for x in my_list):
print(ind)
N2
for id in my_list:
ind = my_list.index(id)
try:
if id == (my_list[ind+1])-1 and id :
print(id)
except IndexError:
print("out of", id)
Thank you in advance.
Upvotes: 0
Views: 280
Reputation: 3229
It sounds like you want to take a list as input and generate a new list that only contains elements of the original that are 10 away from another element in the original.
my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]
new_list = list(filter(lambda x: x + 10 in my_list or x - 10 in my_list, my_list))
Here is a simple way to do just that using python's filter
method.
Results:
[18, 19, 28, 29, 38, 39]
Upvotes: 1