Python:使用给定顺序从dict值创建列表的高效方法 [英] Python: efficient way to create a list from dict values with a given order
本文介绍了Python:使用给定顺序从dict值创建列表的高效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典:
myDict = {age:value1 ,size:value2,'weigth':value3 ...}
我只想要从一个列表中获取一个值列表:按照一个列表定义的顺序:
order_list = [age,weigth,size,...]
所以结果将是:
result_list = [value1,value3,value2,...]
最简单的方法是以这种方式迭代 order_list
for order in order_list:
result_list.append(myDict [key])
但我觉得有一个更有效率和干净的方式来做我正在努力做的事情方法很贵,有两个原因:
- 列列表很长
- 我需要这样做1000次/秒
解决方案
使用列表理解较短:
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返回一个迭代器)
/ pre>
result_list = list(map(myDict。 get,order_list))
#Python 2.x(地图返回列表)
result_list = map(myDict.get,order_list)
I have a dictionary that looks like:
myDict = { "age":value1,"size":value2,'weigth':value3 ... }
And I simply want to get a list of values from this dictionary BUT in some order defined by a list:
order_list = ["age","weigth","size", ... ]
So the result will be:
result_list = [value1,value3,value2, ... ]
The simplest way is to iterate through the
order_list
this way:for key in order_list: result_list.append(myDict[key])
But I beleive that there is a more efficient and clean way to do what I am trying to do as this method is expensive for two reasons:
- The column list is very long
- I need to do this 1000 time / second
解决方案Using a list comprehension is shorter:
myDict = { "age":"value1","size":"value2",'weigth':"value3"} order_list = ["age","weigth","size"] result_list = [myDict[x] for x in order_list]
map
will do as well:# 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)
这篇关于Python:使用给定顺序从dict值创建列表的高效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文