2014-09-24 77 views
1

我已經atext文件和排序數字包含以下內容:與蟒蛇多個小數點

[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 

我需要對它進行排序。由於你看到的數字從1開始,2等已經排序使用排序( )。但像'02 .04.03.02 @@'這樣的數字被單獨排序。但邏輯上它應該在1.之後。如何在Python中執行此操作?我在''分裂嗎?'然後單獨比較?

回答

4

拆分和映射到整數的鍵:

sorted(inputlist, key=lambda v: [int(i) for i in v.rstrip('@').split('.')]) 

這產生每一行整數列表,而這些都是然後按字典順序排序;例如在不同的第一個元素上。

演示:

>>> sample = '''\ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... [email protected]@ 
... '''.splitlines() 
>>> from pprint import pprint 
>>> sorted(sample, key=lambda v: [int(i) for i in v.rstrip('@').split('.')]) 
['[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@', '[email protected]@'] 
>>> pprint(_) 
['[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@', 
'[email protected]@'] 
+0

會'鍵=拉姆達X:浮子(x.rstrip( 「@」))'是整數的列表中的可接受的替代? – inspectorG4dget 2014-09-24 09:35:16

+1

@ inspectorG4dget:不,因爲這裏有3個組件的數字,它們不是有效的浮點數。 – 2014-09-24 09:36:00

+0

當我在代碼中嘗試時,它拋出「ValueError:int()與基數爲10的無效文字:'\ x02'」@MartijinPieters – Nijesh 2014-09-24 10:10:26