Reputation: 66214
I would like to get an array slice that has two (or more) discontiguous parts.
Example:
>>> a=range(100)
>>> a[78:80; 85:97] # <= invalid syntax
[78, 79, 85, 86]
That syntax is not accepted. What's the best way to do it?
UPDATE: Above example was on int
, but I'd primarily like this to work on strings.
Example:
>>> a="a b c d e f g".split()
>>> a[1:3; 4:6]
['b', 'c', 'e', 'f']
Upvotes: 2
Views: 971
Reputation: 32189
An alternative to sberry's answer (although I personally think his is better): Maybe you can use itemgetter
:
from operator import itemgetter
a="a b c d e f g".split()
>>> print itemgetter(*range(1,3)+range(4,6))(a)
['b', 'c', 'e', 'f']
from operator import itemgetter
a="a b c d e f g".split()
items = itemgetter(*range(1,3)+range(4,6))
>>> print items(a)
['b', 'c', 'e', 'f']
Upvotes: 1
Reputation: 132078
What about
>>> a = range(100)
>>> a[78:80] + a[85:97]
[78, 79, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96]
Update: Not sure what you want as the output for your string example:
>>> import string
>>> a = list(string.lowercase[:7])
>>> a[1:3] + a[4:6]
['b', 'c', 'e', 'f']
Upvotes: 4