python3中数字和字符混合列表的三种TypeError

花间影清欢课程 2024-03-29 23:40:30
当列表中混合了数字和字符时,python2.x版本中会将字符按照ASCII码转换后进行操作,但是在python3是不会进行转换,因此会导致报错。 一、sort操作sort 排序元素。 python2中如果元素有数字和字符串,会按照ASCII码来排序,但在Python3中数字和字符串排序会报TypeError错误。 python 2# ------------------------------------------------------------------------------------------------------# Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> l1 = ['c','b','d','z',1,3,2,5,3]>>> l1.sort()>>> l1[1, 2, 3, 3, 5, 'b', 'c', 'd', 'z']# ------------------------------------------------------------------------------------------------------python3# ------------------------------------------------------------------------------------------------------>>> l1 = ['c','b','d','z',1,3,2,5,3]>>> l1.sort()Traceback (most recent call last): File "", line 1, in l1.sort()TypeError: '<' not supported between instances of 'int' and 'str'# ------------------------------------------------------------------------------------------------------二、max操作max 返回列表中最大的元素,也是存在python3中不能字符串和数字比较的问题。 # ------------------------------------------------------------------------------------------------------# python3:>>> max(l1)Traceback (most recent call last): File "", line 1, in max(l1)TypeError: '>' not supported between instances of 'int' and 'str'>>> max(l2)34# # -----------------------------------------------------------------------------------------------------# python2:>>> l1 = ['a','z',1,3,33]>>> max(l1)'z'# ------------------------------------------------------------------------------------------------------三、min操作返回最小元素 min, 同max。 # ------------------------------------------------------------------------------------------------------# python3>>> min(l1)Traceback (most recent call last): File "", line 1, in min(l1)TypeError: '>' not supported between instances of 'int' and 'str'## ------------------------------------------------------------------------------------------------------# python2>>> min(l1)1# ------------------------------------------------------------------------------------------------------
0 阅读:0