重新排列Python中的列表中的子列表

huangapple go评论58阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年2月24日 13:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定