打印列表的疑問
class Node:
def __str__(self):
return "haha"
print([Node(),Node()])
print(Node())
輸出為
[<__main__.Node object at 0x000000000311A208>, <__main__.Node object at 0x000000000311A358>]
haha
打印列表調用的不是每個元素str嗎?看來不是,那調用的是什么.
一個簡單的實例
在自定義結點的時候,需要實現__lt__()函數,這樣優先隊列才能夠知道如何對結點進行排序.
import queue
import random
q = queue.PriorityQueue()
class Node:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return other.x > self.x
def __str__(self):
return "{}".format(self.x)
a = [Node(int(random.uniform(0, 10))) for i in range(10)]
for i in a:
print(i, end=' ')
q.put(i)
print("=============")
while q.qsize():
print(q.get(), end=' ')
隊列的內部實現是二叉樹形式的堆,它最大的缺點在於合並速度慢.然而實際應用中用到合並的場景並不多.如果非要使用可合並堆,可以用斐波那契堆或者二項堆或者左偏樹等數據結構.
隊列和棧
python列表十分強大,已經完全取代了棧和隊列.只需要如下三個函數.
L.pop(index=len(L)-1) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
L.insert(index, object) -- insert object before index
L.append(object) -> None -- append object to end
簡單來說,就是4個操作:
入棧:stack.append(node)
彈棧:stack.pop()
入隊:queue.append(node)
出隊:queue.pop(0)
python中的mixin概念
mixin可以為類添加一種行為,它類似接口的概念,但是mixin允許實現許多函數.java現在也已經支持接口的默認函數了,這其實就相當於mixin.
它的實現方式是多繼承.java中類的單繼承叫"I am",接口的多繼承叫"I can".
python的運算符重載
python2使用的只有一個返回int的cmp函數,python3換成了"富比較".只要實現了__lt__()函數就已經實現了__gt__,__le__等函數.但是沒有實現eq函數,如下代碼輸出為False,因為沒有實現eq函數.而大於號會調用小於號的實現.
要注意__lt__()函數返回的是bool值.
class Node:
def __init__(self,x):
self.x=x
def __lt__(self, other):
return self.x<other.x
print(Node(5)==Node(5))
可以定義一個Mixin
class ComparableMixin(object):
def __eq__(self, other):
if type(self) == type(None):
if type(other) == type(None):
return True
else:
return False
elif type(other) == type(None):
return False
else:
return not self<other and not other<self
def __ne__(self, other):
return not __eq__(self, other)
def __gt__(self, other):
return other<self
def __ge__(self, other):
return not self<other
def __le__(self, other):
return not other<self
python中的排序
python2中的sort函數有cmp參數,python3中刪掉了,於是只得通過key來指定比較的元素.排序也有兩種方法,list.sort()或者是sorted()內置函數.
import random
def rand():
return int(random.uniform(0, 10))
a = [(rand(), rand(), rand()) for i in range(10)]
print(a)
a.sort(key=lambda x: x[0] + x[1] + x[2])
print(a)
a = sorted(a, key=lambda x: (x[2], x[0], x[1]))
print(a)