Is there a better way to get the nth item in a list?

做~自己de王妃 提交于 2019-12-22 08:09:11

问题


The following two expressions are equivalent:

(third (list 1 2 3 4))

(first (nthcdr 2 (list 1 2 3 4)))

However, using "third," "fourth," "fifth," etc. isn't always practical and (first (nthcdr n list)) seems a little verbose. Is there a way to say something like (item 2 (list 1 2 3 4)) to get the nth item in a list?


回答1:


(nth 3 (list 1 2 3 4))

returns 4th item (zero based!)

According to the HyperSpec:

Accessor NTH

Description:

nth locates the nth element of list, where the car of the list is the “zeroth” element. Specifically,

(nth n list) ==  (car (nthcdr n list))

Examples:

(nth 0 '(foo bar baz)) =>  FOO
(nth 1 '(foo bar baz)) =>  BAR
(nth 3 '(foo bar baz)) =>  NIL
(setq 0-to-3 (list 0 1 2 3)) =>  (0 1 2 3)
(setf (nth 2 0-to-3) "two") =>  "two"
0-to-3 =>  (0 1 "two" 3)



回答2:


NTH works for lists.

ELT works for sequences. Sequences are lists and all kinds of one-dimensional arrays (vector, string, ...).

This means that ELT is the more general accessor, which not only works with lists, but also with one-dimensional arrays.



来源:https://stackoverflow.com/questions/4267288/is-there-a-better-way-to-get-the-nth-item-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!