python 数据结构

map

# init
map_ = {} 
map_ = {"shiyang": 0, "heanni": 1, "china": 2}
# existence
print "shiyang" in map_
# add
print map_["shiyang"]
# delete
map_.pop("shiyang")
#traverse
for k in map_.keys():
    print map_[k]
# clear
map_.clear()

set


# init
set_ = set()
set_ = {"shiyang"}  # equal to set_ = set("shiyang")
# existence
print "heanni" in set_
# add
set_.add("heanni")
# delete
set_.discard("shiyang")
# clear
set_.clear()

list


# list
list_ = ["0", "1", "2"]
# add an element at the end
list_.append("3")
# delete the last element
list_.pop()
# add an element in Kth position
list_.insert(3, "3")
# delete the element in K-th position
list_.pop(0)
# delete a certain element when firstly met from the beginning
list_.remove("1")
reversely print elements in a list
for x in reversed(array):
    print x
    
for x in range(len(array)-1,-1,-1):
    print array[x]
    
for x in array[::-1]:
    print x     

deque

# init
deq = deque([1, 2, 3, 4])
# add an element at the end
deq.append(5)
# delete an element at the end
deq.pop()
# add an element at the beginning
deq.appendleft(0)
# delete an element at the beginning
deq.popleft()

min heap


# min heap
hq = [6, 7, 8, 1, 2, 3, 3]
# init
heapq.heapify(hq)
# add
heapq.heappush(hq, 10)
# delete
heapq.heappop(hq)

shiyang6017
158 声望59 粉丝