我从字典中制作排序列表时遇到了问题.我有这个清单
list = [
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'},
d = {'file_name':'thatfile.flt', 'item_name':'teapot', 'item_height':'6.0', 'item_width':'12.4', 'item_depth':'3.0' 'texture_file': 'blue.jpg'},
etc.
]
Run Code Online (Sandbox Code Playgroud)
我正试图遍历列表并且
当我说排序时,我想像这样创建一个新词典
order = {
'file_name': 0,
'item_name': 1,
'item_height': 2,
'item_width': 3,
'item_depth': 4,
'texture_file': 5
}
Run Code Online (Sandbox Code Playgroud)
它按顺序字典中的值对每个列表进行排序.
在一次执行脚本期间,所有列表可能如下所示
['thisfile.flt', 'box', '8.7', '10.5', '2.2']
['thatfile.flt', 'teapot', '6.0', '12.4', '3.0']
Run Code Online (Sandbox Code Playgroud)
另一方面,他们可能看起来像这样
['thisfile.flt', 'box', '8.7', '10.5', 'red.jpg']
['thatfile.flt', 'teapot', '6.0', '12.4', 'blue.jpg']
Run Code Online (Sandbox Code Playgroud)
我想我的问题是如何从字典中的特定值创建列表,并按照与第一个字典具有相同键的另一个字典中的值对其进行排序?
欣赏任何想法/建议,抱歉为noobish行为 - 我还在学习python /编程
Ale*_*lli 11
第一个代码框具有无效的Python语法(我怀疑这些d =部分是无关的......?)以及不明智地践踏内置名称list.
无论如何,例如:
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7',
'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'}
order = {
'file_name': 0,
'item_name': 1,
'item_height': 2,
'item_width': 3,
'item_depth': 4,
'texture_file': 5
}
Run Code Online (Sandbox Code Playgroud)
一种获得理想结果的好['thisfile.flt', 'box', '8.7', '10.5', '2.2', "red.jpg']方法是:
def doit(d, order):
return [d[k] for k in sorted(order, key=order.get)]
Run Code Online (Sandbox Code Playgroud)