我一直在使用字典制作排序列表时遇到问题。我有以下这个列表:
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.
]
我正在尝试循环遍历该列表并且:
- 从每个字典中创建一个新的列表,其中包含来自字典的项目。(随着用户做出选择,需要附加的项目和数量会有所不同)
- 对列表进行排序
order = {
'file_name': 0,
'item_name': 1,
'item_height': 2,
'item_width': 3,
'item_depth': 4,
'texture_file': 5
}
它按照order字典中的值对每个列表进行排序。
在脚本的一次执行期间,所有的列表可能都是这样的
['thisfile.flt', 'box', '8.7', '10.5', '2.2']
['thatfile.flt', 'teapot', '6.0', '12.4', '3.0']
另一方面,它们可能看起来像这样:
['thisfile.flt', 'box', '8.7', '10.5', 'red.jpg']
['thatfile.flt', 'teapot', '6.0', '12.4', 'blue.jpg']
我想知道如何从一个字典中选取特定的值并根据另一个与第一个字典具有相同键的字典中的值进行排序,以生成一个列表。
非常感谢您提供的任何想法/建议,抱歉我的行为有些新手 - 我还在学习Python / 编程。
namedtuple
类可能比字典更适合您在此处的目的。它在Python 2.6+的collections
模块中,如果您使用的是2.4或2.5版本,请从Python Cookbook获取:http://code.activestate.com/recipes/500261/ - John Fouhy