2

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']

2 Answers 2

4

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']
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but I'd like the solution to work for string as well, e.g., to get a two-part slice on a="a b c d e f g".split(). Added update to original question to clarify.
@Frank: What do you want the output to be of your example for a string?
See updated question: >>> a="a b c d e f g".split() >>> a[1:3; 4:6] ['b', 'c', 'e', 'f']
sberry solution still will work, just add the two lists
1

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']

OR

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.