list 检查项目是否在列表中(Lisp)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6144435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:40:04  来源:igfitidea点击:

Check if item is in a list (Lisp)

listlispcommon-lisp

提问by Jeff

What's a simple way to check if an item is in a list?

检查项目是否在列表中的简单方法是什么?

Something like

就像是

(in item list)

might return trueif item=1and list=(5 9 1 2)and falseif item=7

可能返回true如果item=1list=(5 9 1 2)false,如果item=7

回答by Rainer Joswig

Common Lisp

通用 Lisp

FINDis not a good idea:

FIND不是一个好主意:

> (find nil '(nil nil))
NIL

Above would mean that NILis not in the list (NIL NIL)- which is wrong.

以上意味着NIL不在列表中(NIL NIL)- 这是错误的。

The purpose of FINDis not to check for membership, but to find an element, which satisfies a test (in the above example the test function is the usual default EQL). FINDreturns such an element.

的目的FIND不是检查成员资格,而是查找满足测试的元素(在上面的示例中,测试函数是通常的默认值EQL)。FIND返回这样一个元素。

Use MEMBER:

使用MEMBER

> (member nil '(nil nil))
(NIL NIL)  ; everything non-NIL is true

or POSITION:

POSITION

> (numberp (position nil '()))
NIL

回答by Terje Norderhaug

Use MEMBERto test whether an item is in a list:

使用MEMBER一个项目是否是列表中的测试:

(member 1 '(5 9 1 2))  ; (1 2)

Unlike FIND, it is also able to test whether NILis in the list.

与 不同FIND,它还可以测试是否NIL在列表中。

回答by khachik

You can use find:

您可以使用find

(find 1 '(5 9 1 2)) ; 1
(find 7 '(5 9 1 2)) ; nil

Consider using :testargument:

考虑使用:test参数:

(find "a" '("a" "b") :test #'equal)