按 LISP 中的索引号从最大值到最小值对列表进行排序?

标签 sorting indexing lisp elisp common-lisp

我正在尝试编写一个函数,它接受一个列表,将其从高到低排序,然后给出列表中元素的原始位置,从高到低排序。另外,我希望返回的列表中没有重复项。

所以..

(LargestNumberIndex '( 1 23 101 5 6 5 )

应该返回

(2 1 4 3 5 0)

不是

(2 1 4 3 3 0)

目前我的函数看起来像这样:

    (defun LargestNumberIndex (listofnums Indexes) 
  ;; make a copy of the list to sort
  (setf listcopy (copy-list listofnums))
  ;; sort list from high to low
  (setf sortlist (sort listcopy #'>))
  ;; compare the elements from both lists to determine the
  ;; position     
  (loop for i from 0 below Indexes collect
       (position (nth i sortlist) listofnums :test #'equal))

  ))

我不知道要添加什么才能让它工作。有人有什么想法吗?

最佳答案

备注

  • 不要对局部变量使用 SETF 或 SETQ(使用 LET)
  • 对代码进行缩进和格式化
  • 在名字中使用破折号,不要使用 CamelCase
  • LOOP 可以遍历列表:不要像以前那样使用 NTH

修饰、排序、取消修饰

(也称为 Schwartzian transform)

(defun largest-number-index (list)
  (mapcar #'second
          (stable-sort
            (loop
              for index from 0
              for element in list
              collect (list element index))
            #'>
            :key #'first)))

(largest-number-index '(1 23 101 5 6 5))
=> (2 1 4 3 5 0)

关于按 LISP 中的索引号从最大值到最小值对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447353/

相关文章:

c++ - 如何对包含 const 值的 vector 进行排序

c++ - 在 C++ 排序中指定比较函数的参数

arrays - 为什么 Lucene 使用数组而不是哈希表作为倒排索引?

java - 没有 Java 的 Android

Python - 对列表字典中的值进行排序

javascript - 检查属性名称是否为数组索引

c# - Lucene.Net 写/读同步

lisp - 如何通过知道其在 lisp 中的位置来查找列表元素?

functional-programming - 为什么项目选择 Lisp?

Javascript 按字符串属性排序元素不起作用