3

element因此,我需要通过第二个嵌套列表中的第一个(带有 等元素)对这种列表进行排序,其中包含一些随机数据01, 02, 03

  [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], etc]

此随机数据稍后在 defaultdict 中与其他一些数据一起使用,以便将其组合在一起并通过键打印出来(键是数字,如00553, 00551)。

我尝试在将其放入 defaultdict 之前对其进行排序,但我得到的只是嵌套列表本身的值。

谁能帮帮我,我是新来的。

4

3 回答 3

6
>>> lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
>>> sorted(lis, key = lambda x: int(x[1][0])) 
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
于 2013-06-01T20:41:48.623 回答
3

如果您不喜欢lambda一些文档:

L = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
def by_first_of_second(sub_list):
    """First element of second entry as sort key.
       Convert to int to sort by numerical value.
    """
    return int(sub_list[1][0])

sorted(L, key=by_first_of_second)

结果:

[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
于 2013-06-01T20:57:35.263 回答
2
lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']],
      ['00551', ['02', '5.3']], ['00551', ['01', '5.3']],['00551', ['04', '5.3']]]
import operator
newlist = sorted(lis, key=operator.itemgetter(1))

结果

>>> newlist
[['00553', ['01', '3.4']], ['00551', ['01', '5.3']], 
      ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], ['00551', ['04', '5.3']]]
于 2013-06-01T20:51:08.103 回答