Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slicing a list based on values

Tags:

python

list

I have a sorted list (without duplicates) in python, like so,

l = [1, 3, 5, 8, 9, 11, 13, 17]

I would like a take a slice of this based on the list values. So if the value of interest is say, 5. Then I want to locate this value in the list and get 3 values before it in the list.

I can get to my objective with the following function

def f(k):
    if k in l:
        i = l.index(k)
        return (l[i-2:i+1])
    else:
        pass


print (f(5))

[1, 3, 5]


print (f(13))

[9, 11, 13]

However, I have two problems. I do not know what I should do if the value of interest is not a list member. f(6) should also return [1,3,5]. I don't know how to locate 6 in this list

Is there some 'pythonic' way to do this

like image 903
nitin Avatar asked Jan 09 '23 18:01

nitin


2 Answers

you can use:

 less_values = [x for x in l if x < 5]

this should you give an new list with all values smaller than 5

and there you can easily select the last 3 values

like image 145
MrSunday Avatar answered Jan 15 '23 15:01

MrSunday


I'll take a stab that since the list is sorted, and without duplicates, then you're supposed to be using some form of binary search. Python conveniently has a bisect module as part of the standard library.

Code:

import bisect

data = [1, 3, 5, 6, 8, 9, 11, 13, 17]
for val in range(19):
    pos = bisect.bisect_right(data, val)
    print val, '->', data[max(0, pos-3):pos]

Output:

0 -> []
1 -> [1]
2 -> [1]
3 -> [1, 3]
4 -> [1, 3]
5 -> [1, 3, 5]
6 -> [3, 5, 6]
7 -> [3, 5, 6]
8 -> [5, 6, 8]
9 -> [6, 8, 9]
10 -> [6, 8, 9]
11 -> [8, 9, 11]
12 -> [8, 9, 11]
13 -> [9, 11, 13]
14 -> [9, 11, 13]
15 -> [9, 11, 13]
16 -> [9, 11, 13]
17 -> [11, 13, 17]
18 -> [11, 13, 17]
like image 32
Jon Clements Avatar answered Jan 15 '23 13:01

Jon Clements