在Python2中允许对混合变量类型进行排序,但在Python3中不允许?
我正在将脚本从Python2.7升级到Python3.6,但问题是排序不允许使用不同的类型。以前,它将字符串放在一端,数字(int、float等)放在另一端 在Python3中是否有类似于Python2的训练 Python 2.7.13:在Python2中允许对混合变量类型进行排序,但在Python3中不允许?,python,python-3.x,Python,Python 3.x,我正在将脚本从Python2.7升级到Python3.6,但问题是排序不允许使用不同的类型。以前,它将字符串放在一端,数字(int、float等)放在另一端 在Python3中是否有类似于Python2的训练 Python 2.7.13: >>> x = [1, 'a'] >>> x.sort() >>> x [1, 'a'] Python 3.7.3: >>> x = [1, 'a'] >>> x.so
>>> x = [1, 'a']
>>> x.sort()
>>> x
[1, 'a']
Python 3.7.3:
>>> x = [1, 'a']
>>> x.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
定义了一个键,它是列表的第二个元素,因为
results
表示列表的列表。在python 2中,对列表进行排序会导致数据类型通过某种随机硬编码顺序隐式地排序,其中的数据类型比其他数据类型“少”。这种隐式排序在python 3中消失了-相反,您需要通过指定键来显式排序:
# [].sort(key=...) and sorted([], key=...) both work
k = sorted( [1, "a",2,"b"], key=lambda x:type(x).__name__)
print(k)
输出:
[1, 2, 'a', 'b']
[['0285', 13.98], ['2746', 13.98], 'delete', 'delete', 'delete']
编辑列表的列表:
k = sorted( ['delete', 'delete', ['0285', 13.98], ['2746', 13.98], 'delete'],
key=lambda x:type(x[1]).__name__)
# you could also use key=lambda x:type(x).__name__ - it wouldthen use list/str as key
# instead of int/str for type(x[1]).__name__
print(k) #
输出:
[1, 2, 'a', 'b']
[['0285', 13.98], ['2746', 13.98], 'delete', 'delete', 'delete']
Doku:
相关的:
如果我对列表进行排序,并想对每个列表的第二个元素进行排序,会得到TypeError:'@thierrylahuillefixed@Usersort()
和sorted()
都使用键参数-sort()
sortedinplace-sorted()
返回一个新列表,使用其中一个one@User如果需要多个排序条件,请使用tuplelambda x:(键入(x)。\uuuu name\uuuux[1])
进行排序。如果是相同的\uuuuu name\uuuuu
,则另一个参数将规则排序-具有创造性。也许你应该坐下来想想你到底想发生什么,这是你问题的第三个“变化”。。。上面的元组将根据其中的第二个字符对字符串进行排序,并根据浮点对内部列表进行排序。如果您需要满足更多条件并将函数用作键,您可能应该编写一个函数而不是lamdba。。。成功了cleaner@aws_apprentice无论它在Python2中做什么。你想让我用python 2运行它吗?@aws\u学徒完成了