Common lisp 使用lisp获取字符串在列表中的位置
我定义了一个名为Common lisp 使用lisp获取字符串在列表中的位置,common-lisp,Common Lisp,我定义了一个名为*words\u list*的列表,其内容是(“土豆”“食物”“面包”) 我想得到其中一个元素的索引,比如“面包”。 为此,我使用 (setq word_index (position 'bread *words_list*)) 我一直将NIL作为返回值..而元素确实存在于列表中。 我遗漏了什么?要得到你想要的东西,你需要:test: (position 'bread *words_list* :test #'string-equal) 请注意,'bread是一个符
*words\u list*
的列表,其内容是(“土豆”“食物”“面包”)
我想得到其中一个元素的索引,比如“面包”。
为此,我使用
(setq word_index (position 'bread *words_list*))
我一直将NIL
作为返回值..而元素确实存在于列表中。
我遗漏了什么?要得到你想要的东西,你需要
:test
:
(position 'bread *words_list* :test #'string-equal)
请注意,
'bread
是一个符号
,而“bread”
是一个字符串
,因此它们不是eql
(这是默认的:test
谓词)。要获取所需内容,需要:test
:
(position 'bread *words_list* :test #'string-equal)
请注意,
'bread
是一个符号
,而“bread”
是一个字符串
,因此它们不是eql
(这是默认的:test
谓词)。符号bread
不在您的列表中。你可能想要
(定位“面包”单词列表:test#'string=)
(这并不意味着讽刺:理解字符串和符号比以前困难得多,因为语言中没有符号,你不得不用字符串来代替穷人。)符号
面包不在你的列表中。你可能想要
理解符号和字符串之间的区别李>
使用类似于(定位“面包”单词列表:test#'string=)
(这并不意味着讽刺:理解字符串和符号比以前困难得多,因为语言中没有符号,你不得不用字符串来代替穷人。)你有两个问题
首先,列表中的元素是字符串,但您给了位置
一个符号。要纠正这一点,您应该写:
(setq word_index (position "bread" *words_list*))
但是这不起作用,因为POSITION
使用的默认比较函数是EQL
。每次键入字符串文字时,都会创建一个新字符串,即使它们的内容相同,它们也不会相互关联:
(eql "bread" "bread") => NIL
您需要使用:TEST
关键字参数指定比较函数
(setq word_index (position "bread" *words_list* :test #'string=))
如果要进行不区分大小写的比较,请使用string equal
而不是string=
。您有两个问题
首先,列表中的元素是字符串,但您给了位置
一个符号。要纠正这一点,您应该写:
(setq word_index (position "bread" *words_list*))
但是这不起作用,因为POSITION
使用的默认比较函数是EQL
。每次键入字符串文字时,都会创建一个新字符串,即使它们的内容相同,它们也不会相互关联:
(eql "bread" "bread") => NIL
您需要使用:TEST
关键字参数指定比较函数
(setq word_index (position "bread" *words_list* :test #'string=))
如果需要区分大小写的比较,请使用string equal
而不是string=
。bread
是符号,bread
是字符串。bread
是符号,bread
是字符串。