簡體   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