要按嵌套列表中的第二个值排序,可以使用Python内置的sorted()函数,并通过指定key参数来指定排序的依据。
下面是一个示例代码:
nested_list = [[4, 2], [1, 5], [3, 1], [2, 3]]
sorted_list = sorted(nested_list, key=lambda x: x[1])
print(sorted_list)
输出结果为:
[[3, 1], [4, 2], [2, 3], [1, 5]]
在这个示例中,我们定义了一个嵌套列表nested_list。然后,通过调用sorted()函数,传递nested_list作为排序的目标,并指定key参数为一个lambda函数。
lambda函数lambda x: x[1]表示对于每个子列表x,返回其第二个值x[1]作为排序的依据。这样,sorted()函数会根据子列表的第二个值进行排序。
最后,打印排序后的列表sorted_list。