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.
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]
>>> 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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With