python – slicing a list based on values

python – slicing a list based on values

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

Ill take a stab that since the list is sorted, and without duplicates, then youre 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]

python – slicing a list based on values

Pythons array slice notation:

array[:end]      # items from the beginning through end-1

So

array[:5] would be what you needed

So what you could do is:

v = 5
l = [1, 3, 5, 8, 9, 11, 13, 17]
if v in l:
  # do stuff
  print l[:l.index(v)]

Outputs:

[1, 3]

For the guy who negged this:

v = 6
l = [1, 3, 5, 8, 9, 11, 13, 17]
if v in l:
  # do stuff
  print l[:l.index(v)]
else:
  print value is not in the list

Outputs nothing, but that isnt a problem. I just didnt handle the exception with the appropriate else statement.

Leave a Reply

Your email address will not be published.