Home > Software design >  Take a list of numbers and get the three numbers before python
Take a list of numbers and get the three numbers before python

Time:10-11

I have this list of numbers

list1 = [15,27,48,70,83]

I want to have the output

list1 = [12,13,14,15,24,25,26,27,45,46,47,48,67,68,69,70,80,81,82,83]

I know I can do this for each number and then merge the list together and sort them

for i in range(len(list1)):
    list1[i] = list1[i] - 1

Is there a faster way I can do this? Thanks

CodePudding user response:

Do:

list1 = [15,27,48,70,83]

result = [i for e in list1 for i in range(e - 3, e   1)]
print(result)

Output

[12, 13, 14, 15, 24, 25, 26, 27, 45, 46, 47, 48, 67, 68, 69, 70, 80, 81, 82, 83]

The above list comprehension is equivalent to the following nested for-loops:

result = []
for e in list1:
    for i in range(e - 3, e   1):
        result.append(i)

You may face some problems if list1 is not sorted, the goods new is you don't need to sort it, use heapq.merge:

from heapq import merge

list1 = [15, 70, 83, 27, 48]  # not sorted

result = list(merge(*[range(e - 3, e   1) for e in list1]))
print(result)

Using the above approach will keep the overall complexity linear.

CodePudding user response:

Already a nice solution given by @Dani

Here is with numpy

You can play around with numpy if curious

import numpy as np
# For each element add [-3, -2, -1, 0]. possible by adding extra axis
(np.arange(-3, 1)   np.array([15,27,48,70,83])[..., None]).reshape(-1)
  • Related