2016-04-24 24 views
2

字母數字排序混合數據類型的嵌套列表假設我有以下嵌套列表:在Python

nestedlist = [[ 'ABC' , 1.5 , 2 , '8W' ], 
       [ 2 , 'EXT' , 5.8 , '2W' ], 
       [ 'DEF' , 2 , 0.2 , '2Z' ]] 

用於說明我的問題的緣故,我將提到的內列表作爲行(即nestedlist [0 ] = row1,nestedlist [1] = row2等...),並共同從內部列表中共享與列相同的序號索引(即nestedlist [0] [0] = column1的item1,nestedlist [1 ] [0] = column1的item2等...)

如何根據特定列內的值對行進行排序,以便如果按列1排序,則生成的結構將顯示爲li柯如下:

nestedlist = [[ 2 , 'EXT' , 5.8 , '2W' ], 
       [ 'ABC' , 1.5 , 2 , '8W' ], 
       [ 'DEF' , 2 , 0.2 , '2Z' ]] 

如果排序的列2的結構將類似於:

nestedlist = [[ 'ABC' , 1.5 , 2 , '8W' ], 
       [ 'DEF' , 2 , 0.2 , '2Z' ], 
       [ 2 , 'EXT' , 5.8 , '2W' ]] 

如果排序上欄3的結構將類似於:

nestedlist = [[ 'DEF' , 2 , 0.2 , '2Z' ], 
       [ 'ABC' , 1.5 , 2 , '8W' ], 
       [ 2 , 'EXT' , 5.8 , '2W' ]] 

,最後如果上排序第4欄的結構應爲:

nestedlist = [[ 2 , 'EXT' , 5.8 , '2W' ], 
       [ 'DEF' , 2 , 0.2 , '2Z' ], 
       [ 'ABC' , 1.5 , 2 , '8W' ]] 

我知道,如果列中的所有項目都與排序的(嵌套列表,key = itemgetter(sortColIndex))函數可以使用相同的類型,但我不能爲我的生活弄清楚如何得到這個使用混合類型工作。

+0

[natsort函數的Python模擬(使用「自然順序」算法對列表進行排序)]的可能重複(http://stackoverflow.com/questions/2545532/python-analog-of-natsort-function-sort-使用自然順序算法) –

+0

雖然兩者都涉及自然順序排序他們不同,我的問題是問自然排序混合數據類型的嵌套列表,而你提供的鏈接討論解決方案自然地排序單個字符串列表。 –

+0

你有沒有做過任何研究,以排序由某一列嵌套列表?這是一個相當普遍的任務。見[這裏](http://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column),[這裏](http://stackoverflow.com/questions/22698687/how-to- sort-2d-array-numpy-ndarray-based-to-the-second-column-in-python),[here](http://stackoverflow.com/questions/6835531/sorting-a-python-array-recarray除了以上關於自然排序的評論外,還有[這裏](http://stackoverflow.com/questions/409370/sorting-and-grouping-nested-lists-in-python)。 – TigerhawkT3

回答

0

使用Python進行自然排序恬不知恥地複製粘貼:

#!/usr/bin/env python3 
nestedlist = [[ 'ABC' , 1.5 , 2 , '8W' ], 
       [ 2 , 'EXT' , 5.8 , '2W' ], 
       [ 'DEF' , 2 , 0.2 , '2Z' ]] 


import re 
def natural_key(string_): 
    """See http://www.codinghorror.com/blog/archives/001018.html""" 
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] 

sort_column = 0 

print(sorted(nestedlist, key=lambda x: natural_key(str(x[sort_column])))) 

如果你不關心自然排序只是做key=lambda x: str(x[i])。此解決方案在比較之前將任何非字符串轉換爲字符串。

+0

這不會消除浮點數嗎? – TigerhawkT3