-3

I want to find difference between elements of list2 only and only if they are present between elements of list1. Ignore any other case and move to next iteration. I am trying to do this operation in python 3.9

eg: Case 1: 1.2 & 1.6 from list2 are present between 1 & 2 from list1, so difference is saved in new list3 as [0.4]. moving on expected appended list should be [0.4,0.5,0.5] and so on.

Case 2: Between 4 & 5 of list1, there are 3 elements present in list2 i.e - 4.1, 4.5 and 4.9. so ignore this and move to next set of elements of list1.

Case 3: Between 5 & 6 of list1, there is only 1 elements [resent in list2 i.e - 5.5, so ignore this as well since two elements are needed for calculating difference. Hence move to next set of elements in list1.

Case 4: Between 6 & 7 of list1, there are two elements present in list2 i.e 6.2 and 6.3, so append the list3 as - [0.4,0.5,0.5,0.1] and move to next set in list1.

I hope I was able to explain the problem and apologies since it is my first question on StackOverflow community.

list1 = [1,2,3,4,5,6,7]
list2 = [1.2,1.6,2.3,2.8,3.1,3.6,4.1,4.5,4.9,5.5,6.2,6.3]

Expected output -

[0.4,0.5,0.5,0.1]
  • 2
    please post your desired result and your attempt at solving the problem –  Apr 07 '22 at 11:56
  • Where do the two 0.5 in the first case come from? Why is 2, 3 not used as a range? – MisterMiyagi Apr 07 '22 at 11:57
  • It is, between 2 and 3 there are the numbers 2.3 and 2.8 with a difference of 0.5 –  Apr 07 '22 at 11:58
  • I think the expected output is the list : [0.4,0.5,0.5,0.1]. Using pure python, you may solve your problem using loop or list comprehension. – Léo Beaucourt Apr 07 '22 at 12:05

1 Answers1

0

You can get the list2 elements inbetween two list1 elements with a list comprehension:

out = []
for i in range(len(list1)-1):
    inbetweens = [elem for elem in list2 if list1[i] <= elem < list1[i+1]]
    if len(inbetweens) == 2:
        out.append(abs(inbetweens[0]-inbetweens[1]))

print(out)

This outputs:

[0.40000000000000013, 0.5, 0.5, 0.09999999999999964]

If you want to know why it doesn't quite give the right answer, see here

Ukulele
  • 612
  • 2
  • 10