英文:
Rearrange sublists within a list in Python
问题
我有一个包含许多子列表的列表 A
。我想根据每个子列表的第一个元素重新组织这个列表,按升序排列。我呈现当前和预期的输出。
当前输出是
[27, 28, 29, 30]
预期输出是
[[27, 31, 32, 36], [28, 32, 33, 37], [29, 33, 34, 38], [30, 34, 35, 39]]
英文:
I have a list A
containing many sublists. I want to reorganize this list based on the first element of each sublist i.e. in ascending order. I present the current and expected output.
A=[[27, 31, 32, 36], [30, 34, 35, 39], [28, 32, 33, 37], [29, 33, 34, 38]]
C=[]
for i in range(0,len(A)):
B=A[i][0]
C.append(B)
C.sort()
print(C)
The current output is
[27, 28, 29, 30]
The expected output is
[[27, 31, 32, 36], [28, 32, 33, 37], , [29, 33, 34, 38], [30, 34, 35, 39]]
答案1
得分: 2
你可以使用sorted
函数的key
参数以及lambda
关键字创建一个匿名函数,该函数返回列表的第一个元素。
>>> A = [[27, 31, 32, 36], [30, 34, 35, 39], [28, 32, 33, 37], [29, 33, 34, 38]]
>>> sorted(A, key=lambda iterable: iterable[0])
[[27, 31, 32, 36], [28, 32, 33, 37], [29, 33, 34, 38], [30, 34, 35, 39]]
如果只需要按第一个元素排序,sorted
默认情况下就可以实现,所以只需使用sorted(A)
即可。上面介绍的方法适用于所有索引。
英文:
You can use the key
argument to the sorted
function, and the lambda
keyword to create an anonymous function which returns the first element of a list.
>>> A=[[27, 31, 32, 36], [30, 34, 35, 39], [28, 32, 33, 37], [29, 33, 34, 38]]
>>> sorted(A, key = lambda iterable: iterable[0])
[[27, 31, 32, 36], [28, 32, 33, 37], [29, 33, 34, 38], [30, 34, 35, 39]]
For sorting by the first element only, sorted
does this by default, and so just sorted(A)
will do the trick. The method presented above works for all indices.
答案2
得分: 1
你只需要使用sorted
与lambda函数作为键:
C = sorted(A, key=lambda x: x[0], reverse=False)
英文:
So you just need to use sorted
coupled with a lambda function as the key:
C = sorted(A, key=lambda x: x[0], reverse=False)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论