Reputation: 2861
If I have a list for example
A = [0.54,13,18,0,1,1,1,1,0,0,0,1,0]
and I want A[0:1]
and A[3:]
to form
[0.54, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0]
I know if I want a continuous segment in a list , I can do by list[start:end]
but if I want to use several index range in a list but these segments are not continuous, Can I using
list[ ? ]
to achieve?
it seems I can do by A[range1] + A[range2]
thanks
Upvotes: 2
Views: 4342
Reputation: 239473
You can use list comprehension to achieve this.
A = [0.54,13,18,0,1,1,1,1,0,0,0,1,0]
ranges = [(1, 3), (5, 8), (11, 14)]
print ([item for start, end in ranges for item in A[start:end]])
Output
[13, 18, 1, 1, 1, 1, 0]
Upvotes: 7
Reputation: 8147
Simple enough... You are already doing this. Anything else just adds unnecessary fluff. Not sure if there are any performance gains to be had.
>>> A[2:4] + A[7:9]
[18, 0, 1, 0]
To get just one item... Splice just one into a list.
>>> A[2:4] + A[7:9] + A[3:3]
[18, 0, 1, 0]
Upvotes: 2
Reputation: 23364
itertools
may help
from itertools import chain
A = [0.54,13,18,0,1,1,1,1,0,0,0,1,0]
list(chain(A[1:4], A[5:7], A[8:10]))
[13, 18, 0, 1, 1, 0, 0]
Upvotes: 4