排序列表和字典键

时间:2015-05-31 20:13:46

标签: python list python-2.7 dictionary

我使用的是python 2.7,我有这个列表:

photos = ['arthur20.jpg', 'arthur7.jpg', 'arthur11.jpg', 'arthur3.jpg', 'arthur5.jpg', 'arthur17.jpg', 'arthur15.jpg', 'arthur2.jpg', 'arthur13.jpg', 'arthur8.jpg', 'arthur9.jpg', 'arthur18.jpg', 'arthur4.jpg', 'arthur6.jpg', 'arthur10.jpg', 'arthur12.jpg', 'arthur14.jpg', 'arthur19.jpg', 'arthur16.jpg', 'arthur1.jpg']

我如何组织此列表?我尝试使用sort(),但它没有用,它让我回答:

['arthur1.jpg', 'arthur10.jpg', 'arthur11.jpg', 'arthur12.jpg', 'arthur13.jpg', 'arthur14.jpg', 'arthur15.jpg', 'arthur16.jpg', 'arthur17.jpg', 'arthur18.jpg', 'arthur19.jpg', 'arthur2.jpg', 'arthur20.jpg', 'arthur3.jpg', 'arthur4.jpg', 'arthur5.jpg', 'arthur6.jpg', 'arthur7.jpg', 'arthur8.jpg', 'arthur9.jpg']

此外,列表中的字符串也是dict的键,我必须按顺序排列键,如下所示:

dict = {"arthur1.jpg":1, "arthur2.jpg":2 ...}

3 个答案:

答案 0 :(得分:3)

sort()会按照自然顺序对列表进行排序,在本例中为字典排序。您可以按照以下数字对其进行排序" arthur"具有自定义排序功能。最简单的方法是恕我直言,使用正则表达式提取数字:

import re
photos.sort(key = lambda x : int(re.findall('\d+', x)[0]))

对列表进行排序后,创建所需的dict只需zip:{/ p>

from collections import OrderedDict
dict = OrderedDict(zip(photos, range(1, len(photos) + 1)))

答案 1 :(得分:2)

我认为你可能正在寻找处理这些更复杂的排序的natsort包,其中通常的词法排序会失败,因为数字的长度没有被标准化。

>>> natsorted(['arthur20.jpg', 'arthur7.jpg', 'arthur11.jpg', 
               'arthur3.jpg', 'arthur5.jpg', 'arthur17.jpg', 
               'arthur15.jpg', 'arthur2.jpg', 'arthur13.jpg',
               'arthur8.jpg', 'arthur9.jpg', 'arthur18.jpg', 
               'arthur4.jpg', 'arthur6.jpg', 'arthur10.jpg',
               'arthur12.jpg', 'arthur14.jpg', 'arthur19.jpg',
               'arthur16.jpg', 'arthur1.jpg'])
['arthur1.jpg', 'arthur2.jpg', 'arthur3.jpg', 'arthur4.jpg', 
 'arthur5.jpg', 'arthur6.jpg', 'arthur7.jpg', 'arthur8.jpg', 
 'arthur9.jpg', 'arthur10.jpg', 'arthur11.jpg', 'arthur12.jpg',     
 'arthur13.jpg', 'arthur14.jpg', 'arthur15.jpg', 'arthur16.jpg',
 'arthur17.jpg', 'arthur18.jpg', 'arthur19.jpg', 'arthur20.jpg']

答案 2 :(得分:1)

import collections

origdict = {
        4: "four",
        5: "five",
        1: "one",
        2: "two"
    }
od = collections.OrderedDict()

for key in sorted(origdict.keys()):
    od[key] = origdict[key]

print od
相关问题