根据某些元素对列表进行排序
我是 Lisp 的新手,我想学习 Lisp 编程。 我想对从文本文件读取的一些列表进行排序,如下所示:
(a 120 135 124 124)
(b 120 135 124 124)
(c 120 135 124 124)
根据第一个整数元素或第二个或第三个整数元素对它们进行排序的最佳方法是什么?
我有以下想法:
- 将它们全部读取并将它们放入列表列表中,
- 迭代容器列表并将列表的值与下面的值进行比较,就像冒泡排序一样。
是否有更合适的数据结构来实现这一点,也许像Java中的集合一样,它采用包含排序逻辑和自动完成排序的可比对象?
非常感谢。
I am a newbie in Lisp and I want to learn Lisp programming.
I want to sort some lists read from a text file, like in the following form:
(a 120 135 124 124)
(b 120 135 124 124)
(c 120 135 124 124)
What is the best way to sort them according to the first integer element or maybe second or third and so on?
I have the following idea:
- read them all and put them into a list of lists
- iterate over the container list and compare the values of list with following one like in bubble sort.
Are there more suitable data structures to achieve this, maybe like Collections in Java which take comparable objects that contain sort logic and fullfill sorting automatically?
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准
sort
函数采用:key
参数,该参数可用于从对象中提取值以用作排序键。对于您的示例,如果文件中的每个列表都位于名为objects
的列表中,则以下代码将按第一个整数元素对objects
进行破坏性排序,并返回排序后的列表:请参阅http://l1sp.org/cl/sort 了解 Common Lisp 的
sort
函数的精确规范。The standard
sort
function takes a:key
argument that can be used to extract a value from the object to use as the sort key. For your example, if you had each list from the file in a list calledobjects
, the following would destructively sortobjects
by the first integer element and return a sorted list:See http://l1sp.org/cl/sort for the precise specification of Common Lisp's
sort
function.测试:
Test: