小编tar*_*967的帖子

在Python中对2D列表进行排序

我有一个2D列表:

mylist = [[9,7, 2, 2], [1,8, 2, 2], [2,9, 2, 2]]
Run Code Online (Sandbox Code Playgroud)

使用排序功能,列表的排序方式如下:

[[1, 8, 2, 2], [2, 9, 2, 2], [9, 7, 2, 2]]
Run Code Online (Sandbox Code Playgroud)

但我想这样排序这个列表:

[[9, 7, 2, 2],[1, 8, 2, 2], [2, 9, 2, 2]]
Run Code Online (Sandbox Code Playgroud)

而不是列表的第一个数字,我想用最后一个数字排序,就像使用排序函数 - 它按列表的第一个数字排序.我想按最后一个数字排序,比如7小于8和9,所以7先来.

python sorting list

4
推荐指数
1
解决办法
103
查看次数

为什么+运算符创建一个新列表但+ = not

>>> List1 = [1,2,3,4,5]  #Normal List
>>> list2 = list1        
>>> list1 is list2       #list2 is also pointing to the same location as list1
True
Run Code Online (Sandbox Code Playgroud)

但是当我们使用+运算符时,它会创建一个新列表

>>> list2 = list2 + [5]  #adding a list to list2
>>> list1 is list2       #list1 is not pointing to the same location as list2
False
>>> list2                #list2 is modified
[1, 2, 3, 4, 5, 5]
>>> list1                #but list1 is same as before
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

但是当我们使用+ =运算符时,它不会创建新的列表

>>> list2 …
Run Code Online (Sandbox Code Playgroud)

python list

-1
推荐指数
1
解决办法
54
查看次数

标签 统计

list ×2

python ×2

sorting ×1