我有一个像这样的字典:
original_dict = {'two':'2','three':'3','one':'1','foo':'squirrel'}
Run Code Online (Sandbox Code Playgroud)
我想要两个按此顺序:
ordered_dict = OrderedDict({'one':'1','two':'2','three':'3','foo':'squirrel'})
但我没有得到相同的顺序,
{'one':'1','two':'2','three':'3','foo':'squirrel'}自己创建一个字典,所以它不像我说的那样工作
我在文档中看到可以使用已排序的方法
OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
Run Code Online (Sandbox Code Playgroud)
但我不知道一个函数来返回我想要的命令
ordered_dict = OrderedDict(sorted(original_dict.items(),['one','two','three','foo']))
Run Code Online (Sandbox Code Playgroud)
但那没用.
请注意,我想要的顺序可以是任意的,例如:
['three','foo','one','two',]
Run Code Online (Sandbox Code Playgroud) 我想ReverseSort在 上创建一个方法sort.IntSlice。所以我创建了一个自定义类型并为其MySlice添加了一个方法。ReverseSort
package main
import (
"fmt"
"sort"
)
type MySlice sort.IntSlice
func (ms MySlice) ReverseSort() {
sort.Sort(sort.Reverse(ms))
}
func main() {
t2 := MySlice{5, 4, 3, 1}
t2.ReverseSort()
fmt.Println(t2)
}
Run Code Online (Sandbox Code Playgroud)
但运行该程序时显示错误
cannot use ms (type MySlice) as type sort.Interface in argument to sort.Reverse:
MySlice does not implement sort.Interface (missing Len method)
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以实现这一点Len,而无需为我的自定义类型创建自己的Swap和Less方法。