Python 如何優雅的排序與去重

2021-10-02 05:30:11 字數 2939 閱讀 8576

過載實現 __hash__方法和__eq__方法

函式原型:

def

__hash__

(self)

:return

[some hash value]

def__eq__

(self,other)

:#equality

ifisinstance

(other,

[classname]):

#judge type is legal

return

[true

o***lse

]# do your judge there are equality ?

else

:return

false

過載實現 __cmp__方法

函式原型

def

__cmp__

(self ,other):if

isinstance

(other,

[classname]):

# do your judge and return -1 or 0 or 1

else

:raise exception(

"type error"

)return

0

import random

class

stu(

object):

def__init__

(self, stid=

0, stname="")

: self.

id= stid

self.name = stname

def__eq__

(self, other):if

isinstance

(other, stu)

:# do your judge and return -1 or 0 or 1

return self.

id== other.

idelse

:return

false

def__hash__

(self)

:return

hash

(self.id)

def__cmp__

(self, other):if

isinstance

(other, stu)

:# do your judge and return -1 or 0 or 1

return self.

id.__cmp__(other.id)

else

:raise exception(

"type error"

)return

0def

__repr__

(self)

:return self.name +

"\'s id was:"

+str

(self.id)

+"\n"

stuset =

set(

)stulist =

for i in

range(0

,10):

# if you want use random plase import random first

temstu = stu(random.randint(1,

6),"bob"

+str

(random.randint(1,

4)))

stuset.add(temstu)

print

("the set was"

)print

(stuset)

print

("\n\nbefore sort list was:"

)print

(stulist)

stulist.sort(

)print

("after sort list was:"

)print

(stulist)

set的作用是去重,我將10個stu的id設定為1~6的隨機數,那麼肯定有重複的,因此set裡的元素個數 一定<=6,list裡面就一定是10個

下面是執行結果:

set(

[bob3's id was:1

, bob2's id was:4

, bob4's id was:5

, bob1's id was:6])

before sort list was:

[bob2's id was:4

, bob3's id was:1

, bob4's id was:1

, bob1's id was:6

, bob2's id was:6

, bob3's id was:4

, bob2's id was:6

, bob2's id was:6

, bob4's id was:5

, bob3's id was:1

]after sort list was:

[bob3's id was:1

, bob4's id was:1

, bob3's id was:1

, bob2's id was:4

, bob3's id was:4

, bob4's id was:5

, bob1's id was:6

, bob2's id was:6

, bob2's id was:6

, bob2's id was:6

]

優雅的python 寫排序演算法

arr while true 輸入資料 當輸入q結束 a raw input if a q break s len arr for i in range s 氣泡排序 for j in range s i 1 if arr j arr j 1 arr j arr j 1 arr j 1 arr j ...

Python專案中如何優雅的import

wxoa tree cl main.py test wxoa init py pycache init cpython 35.pyc entity init py pycache init cpython 35.pyc user.cpython 35.pyc user.py util init py...

python如何同時對兩個字段優雅的排序

目錄 方法一 最憨厚的排序 方法二 sorted優雅的排序 總結 學無止境 工作中遇到乙個有意思的排序問題,資料結構抽象出來大概是這樣的 乙個列表,列表中的子元素是字典,字典中的key有3個,id表示唯一值元素,count表示某個id在mongodb 現的次數,name表示id對應的名稱,示例如下 ...