这个怎么样:放弃之前的一切,包括@
标志,然后将每个时期分隔的部分为整数。这应该解决数字序列按照字典顺序排序的问题。
>>> array_x = [{'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.11'}, {'title': 'Copy -- @1.3'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}, {'title': 'After -- @1.1'}]
>>> array_x.sort(key=lambda s: list(map(int, s['title'].rpartition("@")[2].split('.'))))
>>> array_x
[{'title': 'After -- @1.1'}, {'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3'}, {'title': 'Copy -- @1.11'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]
编辑:如果你不能保证字符串以数字序列结尾,则代替rpartition,请尝试使用re.findall
从字符串中的任何位置提取的数字:
>>> import re
>>> array_x = [{'title': 'Copy -- @1.1 copy file'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}, {'title': 'After -- @1.1'}]
>>> array_x.sort(key=lambda s: list(map(int, re.findall(r"\d+", s['title']))))
>>> array_x
[{'title': 'Copy -- @1.1 copy file'}, {'title': 'After -- @1.1'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]
编辑第2部分:如果您想基于标题的文本内容打破关系,请将其置于数字列表内容的元组中:
>>> array_x.sort(key=lambda s: (list(map(int, re.findall(r"\d+", s['title']))), s['title']))
>>> array_x
[{'title': 'After -- @1.1'}, {'title': 'Copy -- @1.1 copy file'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]
它的关闭!但我需要按照第一个单词字符串和数字排序,因为我有一个不同的第一个单词的赃物,我需要一些像: '[{'title':'After - @ 1.1 copy'},{'title ':'Before - @ 1.1 move'},{'title':'Before - @ 1.2 move'},{'title':'Copy - @ 1.1'},{'title':'Copy - @ 1.2'}]' 但我想我可以分开他们,这么多坦克! – GRojas
它完美的作品!非常感谢! – GRojas
然后你应该把这个答案标记为正确的http://stackoverflow.com/help/someone-answers – e4c5