繁体   English   中英

从 LISP 列表中删除 NIL

[英]Removing NIL's from a list LISP

简单的问题。

假设我的列表 q 中有一堆 NIL。 有没有一种简单的方法可以删除 NIL 并保留数字? eval 似乎在这里不起作用。

(NIL 1 NIL 2 NIL 3 NIL 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))

如果你正在使用Scheme,这将很好地工作:

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

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

(remove-if-not #'identity list)

正如我在上面的评论中所指出的,我不确定你使用的是哪种Lisp方言,但是你的问题完全符合过滤函数的模型(Python 在这里有过滤器的良好文档)。 从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)))))

当然假设你的Lisp解释器没有内置的过滤器功能,我怀疑它确实如此。 然后,您可以从列表中只保留号码l通过调用

(filter number? l)

暂无
暂无

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

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