开发者

How to get the oddly indexed elements in a list in mathematica

How to get the oddly indexed elements in a list? I am thinking of Select,开发者_开发问答 but did not find anything returning an element's position, especially considering there are repetitive elements in the list.

Also in general, how to select those elements whose indices satisfy some certain conditions?


Here's a few more in addition to @belisarius's answer, which don't require computing Length[lis]:

Take[lis, {1, -1, 2}]

lis[[1 ;; -1 ;; 2]]

You can often use -1 to represent the "last" position.


There are a lot of ways, here are some of them:

In[2]:= a = Range[10];le = Length@a;

In[3]:= Table[a[[i]], {i, 1, le, 2}]

In[5]:= Pick[a, Table[Mod[i, 2], {i, 1, le}], 1]

In[6]:= a[[1 ;; le ;; 2]]

In general, with Pick[] (as an example) you can model any conceivable index mask.


For some reason the terse form of Span has been omitted from the answers.

Range[20][[;;;;2]]
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}

Quoting the documentation:

;;;;k 
from the beginning to the end in steps of k.  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜