根据 Mahtematica 中内部列表元素的字母顺序对列表列表进行排序
我有一个列表列表,其中的内部列表可能具有可变长度。我需要根据内部列表元素的字母顺序对外部列表进行排序。例如,给定
{{0, 0, 7}, {5, 0, 2, 3}, {0, 0, 10, 0}, {0, 6, 2}, {5, 1, 2}, {0, 3, 6, 1, 4}}
我希望 Sort
之后的输出为
{{0, 0, 10, 0}, {0, 0, 7}, {0, 3, 6, 1, 4}, {0, 6, 2}, {5, 0, 2, 3}, {5, 1, 2}}< /code>
我只是不知道如何处理内部列表的可变长度以便编写比较函数。请帮忙。
编辑
顺便说一句,原始列表是一个数字列表。
编辑 2
例如,我有一个列表:
{{0, 0, 7}, {5, 0, 2, 3}, {0, 0, 11, 0}, {0, 0, 1, 12}, {0, 6, 2}, {5, 1, 2}, {0, 3, 6, 1, 4}}
输出应为:
{{0, 0, 1, 12}, {0, 0, 11, 0}, {0, 0, 7}, {0, 3, 6, 1, 4}, {0, 6, 2 }, {5, 0, 2, 3}, {5, 1, 2}}
原因是1
在词法上小于11
,即小于比7
。
I have a list of lists with inner lists possibly of variable lengths. I need to sort the outer list based on the alphabetical order of the inner list elements. For example, given a list of
{{0, 0, 7}, {5, 0, 2, 3}, {0, 0, 10, 0}, {0, 6, 2}, {5, 1, 2}, {0, 3, 6, 1, 4}}
I want the output after Sort
to be
{{0, 0, 10, 0}, {0, 0, 7}, {0, 3, 6, 1, 4}, {0, 6, 2}, {5, 0, 2, 3}, {5, 1, 2}}
I just do not know how to handle the variable lengths of inner lists in order to write a comparison function. Please help.
Edit
BTW, the original list is a numerical one.
Edit 2
For example, I have a list:
{{0, 0, 7}, {5, 0, 2, 3}, {0, 0, 11, 0}, {0, 0, 1, 12}, {0, 6, 2}, {5, 1, 2}, {0, 3, 6, 1, 4}}
The output should be:
{{0, 0, 1, 12}, {0, 0, 11, 0}, {0, 0, 7}, {0, 3, 6, 1, 4}, {0, 6, 2}, {5, 0, 2, 3}, {5, 1, 2}}
The reason is that 1
is lexically less than 11
, which is less than 7
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以像这样设置词典编排比较器:
然后您可以使用它进行排序以获得所需的效果:
如果您希望在排序时将数字视为字符串,您可以像这样修改它:
下面是这种排序的示例:
You can set up a lexciographic comparator like this:
You can then sort using that to get the desired effect:
If you wish to treat the numbers as strings in your sorting, you can modify it like so:
Here is the example of such a sort:
这是通过为默认的
Ordering
排序准备数据,然后使用该顺序对原始列表进行排序来实现的。在这种情况下,将所有列表填充到相同的长度可以防止此
Sort
属性受到干扰:ToString
用于获取字母顺序而不是数字顺序。This works by preparing the data for the default
Ordering
sort, and then using that order to sort the original list.In this case, padding all of the lists to the same length keeps this
Sort
property from interfering:ToString
is used to get an alphabetical order rather than a numeric one.这应该可以做到
这一点之所以有效,是因为从词法上来说,逗号和空格位于数字之前,因此 {a,b} 在词法上位于 {a,b,c} 之前。
This should do it
This works because lexically, comma and space precede the numbers, so {a,b} is lexically before {a,b,c}.