我想对下面的对象列表进行排序,以便返回列表按照提供的键列表的顺序包含对象。例如:
Given object list:
my_list==> [{"ipnetworkaddress", [], "33.33.123.148"}, {"httpbrowsertype", [], "Mozilla"}, {"hostname", [], "example.com"}]
Given order list having object first attribute for criteria:
ordered_keys ===> ["hostname", "httpbrowsertype", "ipnetworkaddress"]
Desired result ==> [{"hostname", [], "example.com"}, {"httpbrowsertype", [], "Mozilla"}, {"ipnetworkaddress", [], "33.33.123.148"} ]
Run Code Online (Sandbox Code Playgroud)
Enum.sort_by/3是你的朋友。
Enum.sort_by(my_list, &Enum.find_index(keys, fn e ->\n e == elem(&1, 0)\nend), &<=/2)\n#\xe2\x87\x92\xc2\xa0[\n# {"hostname", [], "example.com"},\n# {"httpbrowsertype", [], "Mozilla"},\n# {"ipnetworkaddress", [], "33.33.123.148"}\n# ]\nRun Code Online (Sandbox Code Playgroud)\n这不是性能最好的解决方案,但却是最干净的解决方案,对于相对较短的列表来说,\xe2\x80\x99 已经足够好了。
\n对于要排序的列表中的每个元素,我们找到其第一个元素在元组中的索引,并使用该索引按升序进行比较。
\n