python 3.x中列表排序问题,从python2.x过渡到python3.x

 

我也刚学python不多久,所以是学的最新版的3.1,发现有很多规则都和2.x的不一样,最最基本的print都改了,恐怕想把以前的工程移植到3.x没有哪个工程是不需要改动的,感觉python有点失败。。。

 

接下来说下我遇到的问题,本来想学下lambda用法(现在还没搞明白),就在网上找了个例子,如下(print语法我已经改了):

class People: age=0 gender=’male’ def __init__(self, age, gender): self.age = age self.gender = gender def toString(self): return ‘Age:’+str(self.age)+’/tGender:’+self.gender List=[People(21,’male’),People(20,’famale’),People(34,’male’),People(19,’famale’)] print(‘Befor sort:’) for p in List: print(p.toString()) List.sort(lambda p1,p2:cmp(p1.age,p2.age)) print(‘/nAfter ascending sort:’) for p in List: print(p.toString()) List.sort(lambda p1,p2:-cmp(p1.age,p2.age)) print(‘/nAfter descending sort:’) for p in List: print(p.toString())

 

运行,然后报错:

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,所以修改后代码如下:

class People: age=0 gender=’male’ def __init__(self, age, gender): self.age = age self.gender = gender def toString(self): return ‘Age:’+str(self.age)+’/tGender:’+self.gender def Age(self): return self.age List=[People(21,’male’),People(20,’famale’),People(34,’male’),People(19,’famale’)] print(‘Befor sort:’) for p in List: print(p.toString()) List.sort(key=People.Age) print(‘/nAfter ascending sort:’) for p in List: print(p.toString()) List.sort(key=People.Age,reverse=True) print(‘/nAfter descending sort:’) for p in List: print(p.toString())

 

 

几个需要注意的地方

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

2. sort中的reverse参数,在key之后,布尔型,来指定是否反转排序,以前是在cmp()前加负号实现的

 

 

就此,问题得以解决,也反映出了一些问题,要多看官方文档。

现在学python的真少,而且有很多是学的2.x的,3.x的语法和规则改变太大,入门的人为难了,很可能会学一门语言入门两次,哈哈,我还好直接学3.x

    原文作者:张尔谢尔
    原文地址: https://blog.csdn.net/williamzuii/article/details/4888527
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞