拆分和映射到整數的鍵:
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]@']
會'鍵=拉姆達X:浮子(x.rstrip( 「@」))'是整數的列表中的可接受的替代? – inspectorG4dget 2014-09-24 09:35:16
@ inspectorG4dget:不,因爲這裏有3個組件的數字,它們不是有效的浮點數。 – 2014-09-24 09:36:00
當我在代碼中嘗試時,它拋出「ValueError:int()與基數爲10的無效文字:'\ x02'」@MartijinPieters – Nijesh 2014-09-24 10:10:26