Filter nested list if item exists

Filter nested list if item exists

Browning_Zed
Advocate Advocate
704 Views
4 Replies
Message 1 of 5

Filter nested list if item exists

Browning_Zed
Advocate
Advocate

Hi All,
I again had a need to process the list. There was a need to filter the list if a certain item position exists.

In details:
in each nested list, all items can be numbered according to position like this:

;;   items:   1  2  3     1   2   3      1   2   3      1  2   3        
(setq lst '(("1" a nil) ("2" nil 20.0) (nil nil 30.0) (nil nil 40.0)))

now how to create a new list from the original list if an item with a certain number exists? For example, when executing a function in which the first argument is a list of item number positions, then:

(setq lst '(("1" a nil) ("2" nil 20.0) (nil nil 30.0) (nil nil 40.0)))

(somefunction '(1) lst)
;; =>> '(("1" a nil) ("2" nil 20.0))

(somefunction '(2) lst)
;; =>> '(("1" a nil))

(somefunction '(2 3) lst)
;; =>> '(("1" a nil) ("2" nil 20.0) (nil nil 30.0) (nil nil 40.0))

 

 

0 Likes
Accepted solutions (1)
705 Views
4 Replies
Replies (4)
Message 2 of 5

Kent1Cooper
Consultant
Consultant

For the first two:

(defun TEST (lst pos) (vl-remove-if-not '(lambda (x) (nth (1- pos) x)) lst))

 

(test lst 1)
(("1" A nil) ("2" nil 20.0))

(test lst 2)
(("1" A nil))

(test lst 3)
(("2" nil 20.0) (nil nil 30.0) (nil nil 40.0))

 

That's with a single position number [as just a number].  I'll have to think about the third situation a little....

Kent Cooper, AIA
Message 3 of 5

ronjonp
Mentor
Mentor
Accepted solution

Adding to Kent's solution to take care of the 3rd scenario:

(defun test (lst pos)
  (vl-remove-if-not '(lambda (x) (vl-some '(lambda (y) (nth (1- y) x)) pos)) lst)
)
(setq l '(("1" a nil) ("2" nil 20.0) (nil nil 30.0) (nil nil 40.0)("$" nil nil)))
(test l '(2 3))
;; (("1" A nil) ("2" nil 20.0) (nil nil 30.0) (nil nil 40.0))

 

Message 4 of 5

Browning_Zed
Advocate
Advocate

Thank you for your help, dear sirs.

0 Likes
Message 5 of 5

ronjonp
Mentor
Mentor

@Browning_Zed wrote:

Thank you for your help, dear sirs.


Glad to help 🍻