有没有更好的方法来获取列表中的第n个项目? [英] Is there a better way to get the nth item in a list?

查看:63
本文介绍了有没有更好的方法来获取列表中的第n个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个表达式是等效的:

The following two expressions are equivalent:

(third (list 1 2 3 4))

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

但是,使用第三",第四",第五"等并不总是可行的,并且(first (nthcdr n list))似乎有些冗长.有没有办法说出类似(item 2 (list 1 2 3 4))这样的内容来获取列表中的第n个项目?

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?

推荐答案

(nth 3 (list 1 2 3 4))

返回第4个项目(从零开始!)

returns 4th item (zero based!)

根据 HyperSpec :

访问者 NTH

说明:

Accessor NTH

Description:

nth 定位 list n 个元素, list 是零"元素.具体来说,

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))

示例:

(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)

这篇关于有没有更好的方法来获取列表中的第n个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆