如何在关联字符串列表中找到键的值?

时间:2012-09-08 10:56:23

标签: emacs elisp

我有(buffer-name) . (buffer-file-name)形式的最近关闭文件的关联列表,如下所示:

(("04_-_Emacs.rst" . "/home/boris/pst/wordy/edu/HotKeyPoetry/04_-_Emacs.rst")
 ("lib_bk_files_dirs.py" . "/home/boris/cmp/devs/bk_automates/bk_libs/lib_bk_files_dirs.py")
 ("lib_bk_text_related.py" . "/home/boris/cmp/devs/bk_automates/bk_libs/lib_bk_text_related.py")
 ("lib_bk_media.py" . "/home/boris/cmp/devs/bk_automates/bk_libs/lib_bk_media.py")
 nil)

我想得到一个给定键的值:

(defun ergo-undo-close ()
  (interactive)
  (let ((mylist 
         ;; let's get the keys (buffer names):
         ;; butlast for the last element of this alist is nil
         (butlast (mapcar 'car recently-closed-buffers)))
        baseName
        fileName)
    ;; now let's choose the item to resurrect:
    (setq baseName (ido-completing-read "Open this session closed buffer: " mylist))
    (message baseName) ;; works fine
    ;; and find it's full path:
    (setq fileName (assoc baseName mylist)) ;; <- **Edit**: recently-closed-buffers 
                                            ;; should be here instead of mylist
    (print fileName)
    ;; prints nil -- I expected it to print the pair:
    ;; (find-file (cdr fileName))
    ))

修改

根据以下答案,这是我现在正在使用的内容:

(defun ergo-undo-close-buffer ()
  "Opens some this-session closed buffer."
  (interactive)
  (let* ((mylist (delq nil (delete-dups (mapcar 'car recently-closed-buffers))))
         (baseName (ido-completing-read "Open this session closed buffer: " mylist))
         (fileName (cdr (assoc baseName recently-closed-buffers))))
    (find-file fileName)))

2 个答案:

答案 0 :(得分:2)

您想使用(assoc baseName recently-closed-buffers),因为mylist不是列表。顺便说一句,我还建议您尝试在let中为变量赋值,而不是在setq之后为变量赋值。例如:

(let* ((mylist 
        ;; let's get the keys (buffer names):
        ;; butlast for the last element of this alist is nil
        (butlast (mapcar 'car recently-closed-buffers)))
       (baseName (ido-completing-read "Open this session closed buffer: " mylist))
       (fileName (cdr (assoc baseName recently-closed-buffers))))
  (print fileName))

答案 1 :(得分:1)

(cdr (assoc "04_-_Emacs.rst"
            '(("04_-_Emacs.rst" . "/home/boris/pst/wordy/edu/HotKeyPoetry/04_-_Emacs.rst")
              ("lib_bk_files_dirs.py" . "/home/boris/cmp/devs/bk_automates/bk_libs/lib_bk_files_dirs.py")
              ("lib_bk_text_related.py" . "/home/boris/cmp/devs/bk_automates/bk_libs/lib_bk_text_related.py")
              ("lib_bk_media.py" . "/home/boris/cmp/devs/bk_automates/bk_libs/lib_bk_media.py")
              nil)))