1
|
4578 Views
|
|
5 Total Likes
View groups...
Share
GROUPS:

# Using Span to Extract Multiple Spans from a List

Posted 12 years ago
 Let l1 be a list of 100 elements.  Assume I'm interested in taking several spans from this list, which I wish to have as a single list, say elements 5 through 25, 33 through 55, and 81 through 95.So I can use span to extract all three spans separately: p1 = l1[[5;;25]]p2 = l1[[33;;55]]p3 = l1[[81;;95]]I could then combine these into one list. I'm just wondering if there's a simpler way to do that in one step.I tried these options:l2 = l1[[5 ;; 25, 33 ;; 55, 81 ;; 95]]andl2 = l1[[{5 ;; 25, 33 ;; 55, 81 ;; 95}]]andl2 = l1[[5 ;; 25 && 33 ;; 55 && 81 ;; 95]]None of these worked though. I got different error messages along the lines of:Part::pspec: "Part specification {5;;25,33;;55} is neither a machine-sized integer nor a list of machine-sized integers."Any suggestions?
Sort By:
Posted 12 years ago
 Hey Michael, You may quickly define a small function to handle multiple span in one line: In[1]:= f[data_List, {span__List}] :=Map[data[[ #[[1]] ;; #[[2]] ]] &, {span}]In[2]:= f[Range[100], {{3, 5}, {7, 9}}]Out[2]= {{3, 4, 5}, {7, 8, 9}}This function can handle any number of span functions you want to use. The following argument uses BlankSequence function so it can handle multiple inputs{span__List}which is very handy in this type of question.
Community posts can be styled and formatted using the Markdown syntax.