2014-12-19 136 views
2

MS Word有这种默认的非逻辑编号节的方式,我相信它已经体现了它自己的许多其他地方。我谈的是Python排序非逻辑字符串

...

1.8.1忍者

1.8.2 GAAB

1.9.1富

1.10.1巴阿

...

但操作字符串并希望排序会给下面的命令:

[1.10.1 Baa, 1.8.1 Ninja, 1.8.2 Gaab, 1.9.1 Foo]

是否有解决这个问题的任何简单而美丽的蟒蛇呢?

+0

你需要什么叫做“自然排序”,并且有很多reci实施它的pes和片段。例如,参见[this SO question and its answers。](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – user4815162342

回答

2

您需要lambda三个键部分获得编号即从劈开段编号为获得三个整数:

>>> lst = ['1.10.1 Baa', '1.8.1 Ninja', '1.8.2 Gaab', '1.9.1 Foo'] 
>>> sorted(lst, key=lambda x:([int(x) for x in x.split()[0].split('.')])) 
['1.8.1 Ninja', '1.8.2 Gaab', '1.9.1 Foo', '1.10.1 Baa'] 
1
sorted(section_names, key=lambda x: tuple(map(int, x.partition(" ")[0].split(".")))) 
0

利用这样的元组的顺序排序的事实,你想要:

strList = ["1.8.1 Ninja",               
    "1.8.2 Gaab", 
    "1.9.1 Foo", 
    "1.10.1 Baa"] 

sorted(((tuple(map(int, x.split('.'))), y) # Sort according to list numbers 
      for s in strList 
      for [x, y] in [s.split(' ', 1)]  # [x, y] = s.split(' ', 1) 
               # Splits list in exactly 2 elems 
    )) 

# Out[43]: 
# [((1, 8, 1), 'Ninja'), 
# ((1, 8, 2), 'Gaab'), 
# ((1, 9, 1), 'Foo'), 
# ((1, 10, 1), 'Baa')] 
+0

看看Bhat和我的答案,你可以利用这个事实,而不用'sorted'的'key'参数来改变'list'的元素。 – filmor