Sorting list of lists by particular index of inner lists

六眼飞鱼酱① 提交于 2019-12-10 19:09:09

问题


I have a list that looks something like this:

[["Local 7" 1 "say" "Say: Inspect Fences"] ["Local 7" 1 "do" "Do: Shepherd Cows"] ["Local 6" 1 "say" "Say: Shepherd Cows"] ["Local 6" 1 "do" "Do: Shepherd Cows"] ["Local 6" 2 "say" "Say: Shepherd Cows"] ["Local 6" 2 "do" "Do: Shepherd Cows"] ["Local 7" 2 "say" "Say: Inspect Fences"] ["Local 7" 2 "do" "Do: Shepherd Cows"] ["Local 6" 3 "say" "Say: Shepherd Cows"] ["Local 6" 3 "do" "Do: Shepherd Cows"] ["Local 7" 3 "say" "Say: Inspect Fences"] ["Local 7" 3 "do" "Do: Inspect Fences"]]

I'd like to sort the list by item 1. (I know it already is in the copy/pasted version, but it might not always be.)

sort just returns an empty list (I'm not even sure why, but I guess that's a separate question), and sort-by doesn't seem to work because it needs a reporter that resolves to a boolean.

Is there a clever way to do this? Or would I need to first get a list of the values I want to sort by, then sort that, and then iterate over that list, creating a new list of the values in the original list in which the respective item value matches?


回答1:


Edit: Updated with NetLogo 6 syntax

You can convert this into a sort-by pretty easily:

to-report sort-with [ key lst ]
  report sort-by [ [a b] -> (runresult key a) < (runresult key b) ] lst
end

Then you use it like so:

sort-with [ l -> item 1 l ] my-list


来源:https://stackoverflow.com/questions/31545569/sorting-list-of-lists-by-particular-index-of-inner-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!