混合名單說我有這個名單l = ['the fountainhead','atlas shrugged', 1, 67, 12, 0]
我要進行排序,以便最終的結果是['atlas shrugged', 'the fountainhead', 0, 1, 12, 67]
。這意味着列表中的字符串和整數應按升序排序。如果我使用sorted()
數字出現第一:排序在Python
>>> sorted(l)
[0, 1, 12, 67, 'atlas shrugged', 'the fountainhead']
,如果我用的λ,它不能讓過去的訂貨清單,因爲它包含了不同類型的無與倫比的元素:
>>> sorted(l, key=lambda x:int(x))
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
sorted(l, key=lambda x:int(x))
File "<pyshell#13>", line 1, in <lambda>
sorted(l, key=lambda x:int(x))
ValueError: invalid literal for int() with base 10: 'the fountainhead'
據我所知,使用lambdas時沒有辦法利用異常處理。這只是一個簡單的例子來說明這個問題。我想知道是否有一種靈活的通用方法來對Python中的混合列表進行排序。我在SO上搜索了相關頁面,但找不到一個通用的方法。
好了,檢查對象的類型。如果它是一個數字類型,那麼使用該項目,否則使用'float(' - inf')'。三元表達式可以用於此。 –
你的排序規則是什麼?所有的字符串是否應該在數字前出現或者只是以「a」開頭的字符串? –
@GregHewgill字符串需要先出現。 – Omid