Python中有趣的数据结构

链表

链表的基本操作

>>> a = [66.25,333,333,1,1234.5]
>>> print a.count(333),a.count(66.25),a.count('x')
2 1 0
>>> a.insert(2,-1)
>>> a
[66.25, 333, -1, 333, 1, 1234.5]
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]

把链表当做堆栈来使用

>>> stack = [3,4,5]
>>> stack.append(6)
>>> stack
[3, 4, 5, 6]
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack
[3, 4, 5]
>>> stack.pop()
5
>>> stack
[3, 4]

把链表当做队列使用

>>> from collections import deque
>>> queue = deque(["Tom","Jack","John"])
>>> queue.append("Jiqing");
>>> queue.append("Yinting");
>>> queue.popleft()
'Tom'
>>> queue.popleft()
'Jack'
>>> queue
deque(['John', 'Jiqing', 'Yinting'])

del语句

>>> a = [-1,1,66.25,333,333,1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]

集合

无序,不重复

>>> a = [1,1,2,2,3,3,5,5,4,4,9,8,7]
>>> b = set(a)
>>> b
set([1, 2, 3, 4, 5, 7, 8, 9])
>>> 6 in b
False
>>> 1 in b
True

字典

>>> tel = {'jack':100,'jim':200}
>>> tel['jiqing'] = 300
>>> tel
{'jiqing': 300, 'jim': 200, 'jack': 100}
>>> tel['jiqing']
300
>>> del tel['jim']
>>> tel.keys()
['jiqing', 'jack']
>>> 'jiqing' in tel
True

有趣的语言,Python。

原文地址:https://www.cnblogs.com/jiqing9006/p/9937821.html