我有一个类似的字典:
myDict = { "age":value1,"size":value2,'weigth':value3 ... }
我只是想从列表中获取一个值列表但是按照列表定义的某种顺序:
order_list = ["age","weigth","size", ... ]
结果将是:
result_list = [value1,value3,value2, ... ]
最简单的方法是以这种方式迭代order_list
:
for key in order_list:
result_list.append(myDict[key])
但我相信,有一种更有效,更干净的方式来做我想做的事情,因为这种方法很昂贵有两个原因:
答案 0 :(得分:2)
使用列表理解更短:
myDict = { "age":"value1","size":"value2",'weigth':"value3"}
order_list = ["age","weigth","size"]
result_list = [myDict[x] for x in order_list]
map
也会这样做:
# Python 3.x (map returns an iterator)
result_list = list(map(myDict.get, order_list))
# Python 2.x (map returns a list)
result_list = map(myDict.get, order_list)