Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the slice method to return a list that excludes ranges in the middle of the original list?

Is there a way to slice through a whole list while excluding a range of values or multiple range of values in the middle of the list?
For example:

list = [1,2,3,4,5,6,7,8,9,0]
print list[......] #some code inside  

I'd like the above code to print the list while excluding a range of values so the output would be: [1,2,3,8,9,0] or excluding multiple value ranges so the output would be: [1,2,6,7,0] by using the slice notation or any other simple method you can suggest.

like image 254
Moolla Avatar asked May 26 '13 10:05

Moolla


3 Answers

Use list comprehensions:

>>> mylist = [1,2,3,4,5,6,7,8,9,0]
>>> print [i for i in mylist if i not in xrange(4,8)]
[1, 2, 3, 8, 9, 0]

Or if you want to exclude numbers in two different ranges:

>>> print [i for i in mylist if i not in xrange(4,8) and i not in xrange(1,3)]
[3, 8, 9, 0]

By the way, it's not good practice to name a list list. It is already a built-in function/type.


If the list was unordered and was a list of strings, you can use map() along with sorted():

>>> mylist = ["2", "5", "3", "9", "7", "8", "1", "6", "4"]
>>> print [i for i in sorted(map(int,mylist)) if i not in xrange(4,8)]
[1, 2, 3, 8, 9]
like image 184
TerryA Avatar answered Sep 29 '22 12:09

TerryA


>>> nums = [1,2,3,4,5,6,7,8,9,0]
>>> exclude = set(range(4, 8))
>>> [n for n in nums if n not in exclude]
[1, 2, 3, 8, 9, 0]

Another example

>>> exclude = set(range(4, 8) + [1] + range(0, 2))
>>> [n for n in nums if n not in exclude]
[2, 3, 8, 9]
like image 41
jamylak Avatar answered Sep 29 '22 14:09

jamylak


Using a method, and an exclude list

def method(l, exclude):
    return [i for i in l if not any(i in x for x in exclude)]

r = method(range(100), [range(5,10), range(20,50)])
print r

>>> 
[0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

My example uses ranges with ints. But this method can be any list of items, with any number of exclude lists with other items, as long as the items have an equals comparison.


Edit: A much faster method:

def method2(l, exclude):
    ''' 
    l is a list of items, exclude is a list of items, or a list of a list of items
    exclude the items in exclude from the items in l and return them.
    '''
    if exclude and isinstance(exclude[0], (list, set)):
        x = set()
        map(x.add, [i for j in exclude for i in j])
    else:
        x = set(exclude)
    return [i for i in l if i not in x]
like image 33
Inbar Rose Avatar answered Sep 29 '22 13:09

Inbar Rose