1. 程式人生 > >python 3.x中列表排序問題,從python2.x過渡到python3.x

python 3.x中列表排序問題,從python2.x過渡到python3.x

我也剛學python不多久,所以是學的最新版的3.1,發現有很多規則都和2.x的不一樣,最最基本的print都改了,恐怕想把以前的工程移植到3.x沒有哪個工程是不需要改動的,感覺python有點失敗。。。

接下來說下我遇到的問題,本來想學下lambda用法(現在還沒搞明白),就在網上找了個例子,如下(print語法我已經改了):

執行,然後報錯:

Traceback (most recent call last):
  File "C:/WilliamPythonProj/test.py", line 18, in <module>
    List.sort(lambda p1,p2:cmp(p1.age,p2.age))
TypeError: must use keyword argument for key function

就是在排序那裡出的錯,經過檢視官方文件得出結論:

sorted ( iterable [ , key ] [ , reverse ] )

Return a new sorted list from the items in iterable

.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower . The default value is None .

reverse is a boolean value. If set to True , then the list elements are sorted as if each comparison were reversed.

To convert an old-style cmp function to a key function, see the CmpToKey recipe in the ASPN cookbook .

重點:key指定含有一個引數的函式,這個函式被用來提取各個元素之間比較用的關鍵字(現在看來,這個用法比用lambda更明瞭些)

根據這個提示,終於明白了,我要比較List中每個元素大小,每個元素都是People類,用age成員作為比較關鍵字,所以很簡單聯想到要給key賦一個方法,這個方法返回People中的age,所以修改後程式碼如下:

幾個需要注意的地方

1. sort(key=People.Age),而不是sort(key=People.Age())

2. sort中的reverse引數,在key之後,布林型,來指定是否反轉排序,以前是在cmp()前加負號實現的

就此,問題得以解決,也反映出了一些問題,要多看官方文件。

現在學python的真少,而且有很多是學的2.x的,3.x的語法和規則改變太大,入門的人為難了,很可能會學一門語言入門兩次,哈哈,我還好直接學3.x