|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- >>> b = ["h","e","l","l","o","hello","hell","hel","he"]
- >>> b.sort()
- >>> b
- ['e', 'h', 'he', 'hel', 'hell', 'hello', 'l', 'l', 'o']
- >>> b.sort(reverse=True)
- >>> b
- ['o', 'l', 'l', 'hello', 'hell', 'hel', 'he', 'h', 'e']
复制代码
各位大神 str类排序是依据是啥
- Microsoft Windows [版本 10.0.17763.805]
- (c) 2018 Microsoft Corporation。保留所有权利。
- C:\Users\jx>python
- Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
- Type "help", "copyright", "credits" or "license" for more information.
- >>> a = ["1","2","3","4"]
- >>> a.extend(["hello","python",None]) )
- >>> a
- ['4', '3', '2', '1', 'hello', 'python', None]
- >>> a.sort(reverse=True)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: '<' not supported between instances of 'str' and 'NoneType'
- >>> a.remove(None)
- >>> a
- ['4', '3', '2', '1', 'hello', 'python']
- >>> a.sort(reverse=True)
- >>> a
- ['python', 'hello', '4', '3', '2', '1']
复制代码
另外需要各位指教的是 为什么sort方法 存在 None值时 会出现错误 使用 reverse()则可以执行呢?
本帖最后由 jackz007 于 2019-11-17 01:17 编辑
sort() 方法排序依据的是字符串中字符的 ASCII 编码顺序或元素的数值大小,一般是按从小到大的顺序排列。对于字符串元素,首先比较首字符,如果编码相同,则继续比较后续字符,直至决出顺序为止。
sort() 方法需要访问并比较每一个列表元素,而 None 无值,不是一个正常的列表元素,导致比较排序操作无法正常进行。所以,列表中不可以含有 None;reverse() 方法不需要访问元素,只要把列表的元素顺序反过来就可以了,所以,reverse() 方法可以处理带有 None 元素的列表。
|
|