本文介绍了通过多个键对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我可以通过多个排序键在Python中对多维数组进行排序吗?一个

litte代码示例会很好!


Thx,

Rehceb

解决方案



您可以将函数作为参数传递给列表的排序方法。

函数应该接受两个参数并返回-1, 0或1为

比较结果。就像cmp函数一样。


这将通过id属性列出obj_lst中的对象:


def sorter(a,b):

返回cmp(a.id,b.id)


obj_lst.sort(分拣机)


Thomas




如果你想要一个好的答案,你必须给我/我们更多的细节,以及一个

的例子。


再见,

熊宝宝




好​​的,这是一些示例数据:


反应是由

钠,但它是

海,但这是

这种方式但是解散了

模式,但它是

快速,但它是


由于每行包含5个单词,我会将数据分解成数组

的五个字段数组(你会在
Python中使用列表或元组或组合吗?)。单词BUT将在中间,两个字段/单词

左边和两个字段/单词右边。然后我想按这个列表排序


- 字段3

- 字段4

- 字段1

- 字段0

此层次结构中的
。这是理想的结果:


模式,但它是快速的b / b
海,但它是
钠,但它是

反应是由

这种方式但是已经解散了


前4行全部无法按字段3& 4,因为它们是相同的(它,是),所以它们首先按字段1排序(

也是相同的:" ;,&);然后按字段0:


模式

快速






我希望我以一种可以理解的方式对此进行了解释。如果你能告诉我如何用Python做到这一点会很酷




问候,

Rehceb

Hello everyone,

can I sort a multidimensional array in Python by multiple sort keys? A
litte code sample would be nice!

Thx,
Rehceb

解决方案

You can pass a function as argument to the sort method of a list.
The function should take two arguments and return -1, 0 or 1 as
comparison result. Just like the cmp function.

This will objects in list obj_lst by their id attributes:

def sorter(a, b):
return cmp(a.id, b.id)

obj_lst.sort(sorter)

Thomas


If you want a good answer you have to give me/us more details, and an
example too.

Bye,
bearophile


OK, here is some example data:

reaction is BUT by the
sodium , BUT it is
sea , BUT it is
this manner BUT the dissolved
pattern , BUT it is
rapid , BUT it is

As each line consists of 5 words, I would break up the data into an array
of five-field-arrays (Would you use lists or tuples or a combination in
Python?). The word "BUT" would be in the middle, with two fields/words
left and two fields/words right of it. I then want to sort this list by

- field 3
- field 4
- field 1
- field 0

in this hierarchy. This is the desired result:

pattern , BUT it is
rapid , BUT it is
sea , BUT it is
sodium , BUT it is
reaction is BUT by the
this manner BUT the dissolved

The first 4 lines all could not be sorted by fields 3 & 4, as they are
identical ("it", "is"), so they have been sorted first by field 1 (which
is also identical: ",") and then by field 0:

pattern
rapid
sea
sodium

I hope I have explained this in an understandable way. It would be cool
if you could show me how this can be done in Python!

Regards,
Rehceb


这篇关于通过多个键对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:13