简体   繁体   English

从 LISP 列表中删除 NIL

[英]Removing NIL's from a list LISP

Simple question.简单的问题。

Say I have a bunch of NIL's in my list q.假设我的列表 q 中有一堆 NIL。 Is there a simple way to remove the NILs and just keep the numbers?.有没有一种简单的方法可以删除 NIL 并保留数字? eval doesn't seem to work here. eval 似乎在这里不起作用。

(NIL 1 NIL 2 NIL 3 NIL 4)

I need (1 2 3 4)我需要(1 2 3 4)

Common Lisp,而不是remove - 如果你可以使用remove:

(remove nil '(nil 1 nil 2 nil 3 nil 4))

在常见的lisp和其他方言中:

(remove-if #'null '(NIL 1 NIL 2 NIL 3 NIL 4))

If you're using Scheme, this will work nicely: 如果你正在使用Scheme,这将很好地工作:

(define lst '(NIL 1 NIL 2 NIL 3 NIL 4))

(filter (lambda (x) (not (equal? x 'NIL)))
        lst)

(remove-if-not #'identity list)

As I noted in my comment above, I'm not sure which Lisp dialect you are using, but your problem fits exactly into the mold of a filter function (Python has good documentation for its filter here ). 正如我在上面的评论中所指出的,我不确定你使用的是哪种Lisp方言,但是你的问题完全符合过滤函数的模型(Python 在这里有过滤器的良好文档)。 A Scheme implementation taken from SICP is 从SICP获得的Scheme实现是

(define (filter predicate sequence)
  (cond ((null? sequence) nil)
        ((predicate (car sequence))
         (cons (car sequence)
               (filter predicate (cdr sequence))))
        (else (filter predicate (cdr sequence)))))

assuming of course that your Lisp interpreter doesn't have a built-in filter function, as I suspect it does. 当然假设你的Lisp解释器没有内置的过滤器功能,我怀疑它确实如此。 You can then keep only the numbers from your list l by calling 然后,您可以从列表中只保留号码l通过调用

(filter number? l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM