如何在python中按行对2d数组排序

如何在python中按行对2d数组排序

本文介绍了如何在python中按行对2d数组排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2d数组,尺寸为3x10,我想按第二行中的值(从最低到最高)进行排序.

I have 2d array, dimension 3x10, and I want to sort by values in 2nd row, from lowest to highest value.

推荐答案

Python本身没有"2d数组"-它具有(1d)内置列表以及标准库模块中的(1d)数组数组.有一些第三方库,例如numpy,它们确实提供了Python可用的多维数组,但是如果您正在使用其中的某些库,那么您当然会提到此类第三方库,而不仅仅是说在Python中" ,正确?-)

Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module array. There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", right?-)

因此,我假设"2d数组"是指列表列表,例如:

So I'll assume that by "2d array" you mean a list of lists, such as:

lol = [ range(10), range(2, 12), range(5, 15) ]

或类似内容-即包含3个项目的列表,每个项目是包含10个项目的列表,而第二行"将是子列表项目lol[1].是的,有很多假设,但是您的问题是如此的令人困惑,以至于无法避免做出假设-如果您不喜欢试图读懂想法的人(可能是失败的话),请编辑您的Q以更精确地阐明问题,并举一个例子!因为您目前无法避免.

or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item lol[1]. Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.

因此,在这些假设下,您可以按照对第二个子列表进行排序所需的顺序对3个子列表中的每个列表进行排序,例如:

So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:

indices = range(10)
indices.sort(key = lol[1].__getitem__)
for i, sublist in enumerate(lol):
  lol[i] = [sublist[j] for j in indices]

这里的一般方法是对索引范围进行排序,然后使用适当排序的范围对正在播放的所有子列表进行重新排序.

The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.

如果您实际上有其他问题,当然会有不同的解决方案;-).

If you actually have a different problem, there will of course be different solutions;-).

这篇关于如何在python中按行对2d数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:06