max()函数如何在python中的字符串列表上工作? [英] How does the max() function work on list of strings in python?
问题描述
我有一个列表:
list1 = [123, 'xyz', 'zara', 'abc']
print "Max value element : ", max(list1);
它给出:
Max value element : zara
还请说明它如何对字符串列表和数字列表进行比较.
Please also explain how it perform comparison on list of strings and list of numbers.
推荐答案
这实际上是一个好问题,答案取决于您使用的是python2.x还是python3.x ... 以及哪个python您正在使用的实现 1 .
This is actually a good question and the answer varies depending on whether you're on python2.x or python3.x ... And which python implementation you're using1.
请参阅此处,以获取有关python如何比较不同类型的描述.该链接几乎列出了您需要知道的所有内容,但简要说明如下:
See here for a description of how python compares different types. The link says pretty much all that you need to know, but as a quick summary:
- 比较相同类型的对象的行为符合您的预期.
- 不同类型的对象的比较按其在python2.x上的类型名称排序,并在python3.x上引发错误(除非定义了自定义比较运算符.)
- 旧样式的类违反了所有规则,但是无论如何都不应该使用它们.
- comparison of objects of the same type acts as you'd expect.
- comparison of objects of different type are ordered by their type name on python2.x and raise an error on python3.x (Unless a custom comparison operator is defined.)
- old style classes break all the rules but they shouldn't be used anyway.
1 希望您能从不确定性的数量中看出,这个定义不是很好,所以应该避免这种情况.
1Hopefully you can see by the amount of uncertainty there that this is not really well defined and so it's a situation that you should try to avoid.
这篇关于max()函数如何在python中的字符串列表上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!