简体   繁体   中英

slicing a list based on values

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

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

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]

Python's 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 isn't a problem. I just didn't handle the exception with the appropriate else statement.

您可以使用index进行搜索,如下所示:

l.index(5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM