首页 > 解决方案 > 遍历列表以查找数据,并构造一个字符串

问题描述

Elisp新手,寻求帮助。

我有这个变量:

(setq bibtex-completion-additional-search-fields '(tags keywords))

然后我有一个函数,如果设置了这个变量,则需要遍历这些字段名称,并在数据记录中查找它们,将结果值连接成一个字符串,然后返回。

数据如下所示:

("2009-03-01 Zukin, Sharon and Trujillo, Valerie and Frase, Peter and Jackson, Danielle and Recuber, Tim and Walker, Abraham gentrification New Retail Capital and Neighborhood Change: Boutiques and Gentrification in New York City article zukin_new_2009"
 ("date" . "2009-03-01")
 ("author" . "Zukin, Sharon and Trujillo, Valerie and Frase, Peter and Jackson, Danielle and Recuber, Tim and Walker, Abraham")
 ("tags" . "gentrification, retail")
 ("title" . "New {{Retail Capital}} and {{Neighborhood Change}}: {{Boutiques}} and {{Gentrification}} in {{New York City}}")
 ("=type=" . "article")
 ("=key=" . "zukin_new_2009"))

这就是我所拥有的功能 ATM,我知道这是错误的。但是我不知道如何在 elisp 中做到这一点(我对 Python 和 Ruby 有更多的经验)。

(defun bibtex-completion--get-extra-search-data (candidate)
  "Return extended search metadata as string."
  (if bibtex-completion-additional-search-fields
      ; if the data is present, pull its value(s), join into a single string
      ; TODO FIX ME, this is wrong
      (format "%s" (cl-loop
                    for field in bibtex-completion-additional-search-fields
                    collect
                    (cdr (assoc field (cdr candidate)))
                    ))))

因此,对于上面的示例数据,函数应该返回字符串“绅士化,零售”。如果该记录有一个带有“foo”的关键字字段,则返回字符串将是“绅士化,零售,foo”(或者可以只是空格分隔;不确定是否重要)。

标签: stringemacsiteration

解决方案


首先,数据结构中的键是字符串,而不是符号。因此,您可以更改查找字段,

(setq bibtex-completion-additional-search-fields '("tags" "keywords"))

但是,在数据结构中使用符号作为cars可能更好(我相信效率方面)。candidate

将列表加入字符串的规范 elisp (mapconcat #'identity ...)

(mapconcat
 #'identity
 (delq nil
       (cl-loop for field in bibtex-completion-additional-search-fields
             collect (cdr (assoc field (cdr candidate)))))
 ", ")

推荐阅读