2013-10-14 130 views
8

我有一個由這樣的詳細信息列表:排序在Python中 - 如何排序包含字母數字值的列表?

list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"] 
現在

,我想對此列表進行排序,這樣的值是按以下順序:

list1 = ["1", "2C", "36", "100A", "132", "302F", "342B"] 

只是做list1.sort()明顯沒有給出正確的答案 - 它提供:

list1 = ["1", "100A", "132", "2C", "36", "302F", "342B"] 

我假設這是因爲Python將所有這些直接作爲字符串。 但是,我想根據它們的數字值FIRST對它們進行排序,然後根據數字對它們進行排序。

我該如何繼續?

太謝謝你了:)

+0

看到這篇文章(http://stackoverflow.com/questions/11850425/custom-python-list-sorting)並定義一個自定義比較函數。 – lurker

+2

這被稱爲**自然分類**。可能重複的[Python是否有內置的字符串自然排序功能?](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-排序) –

回答

11

你想用natural sort

import re 

_nsre = re.compile('([0-9]+)') 
def natural_sort_key(s): 
    return [int(text) if text.isdigit() else text.lower() 
      for text in re.split(_nsre, s)] 

用法示例:

>>> list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"] 
>>> list1.sort(key=natural_sort_key) 
>>> list1 
['1', '2C', '36', '100A', '132', '302F', '342B'] 

這通過分裂的功能元素融入到列表中分隔出來的號碼,比較它們爲整數,而不是字符串:

>>> natural_sort_key("100A") 
['', 100, 'a'] 
>>> natural_sort_key("342B") 
['', 342, 'b'] 

注意,在Python3這僅適用於如果你總是比較整數和字符串處理字符串整數,否則,你得到一個TypeError: unorderable types例外。

+1

請注意,對於Python 3所有項目必須具有相似的結構。 '['a1','2b']'會因'TypeError'失敗。 –

+0

@StevenRumbalski:啊,我忘記了,謝謝。我會提到它。 – Claudiu

0

好了,你必須找到一種方法,你的第一個字符串轉換爲數字。例如

import re 
def convert(str): 
    return int("".join(re.findall("\d*", str))) 

,然後你用它作爲排序關鍵字:

list1.sort(key=convert) 
+0

這裏有一些更自然的排序解決方案:http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort – nofinator

相關問題