【发布时间】:2010-11-18 03:47:41
【问题描述】:
我在从字典中制作排序列表时遇到了问题。 我有这份清单
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
}
它按照顺序字典中的值对每个列表进行排序。
在一次脚本执行期间,所有列表可能如下所示
['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 获取它:code.activestate.com/recipes/500261
标签: python sorting dictionary