tuoheng_algN/test/collections/OrderedDict.py

35 lines
839 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from collections import OrderedDict
"""
1、popitem
语法popitem(last=True)
功能:有序字典的 popitem() 方法移除并返回一个 (key, value) 键值对。
如果 last 值为真,则按 LIFO 后进先出的顺序返回键值对,否则就按 FIFO 先进先出的顺序返回键值对。
"""
d = OrderedDict.fromkeys('abcde')
print(d)
print(d.popitem())
# #last=False时弹出第一个
print(d.popitem(last=False))
print(d.popitem(last=True))
"""
2、move_to_end
"""
d = OrderedDict.fromkeys('abcde')
d.move_to_end('b')
print(d)
d.move_to_end('b', last=False)
print(d)
"""
3、reversed()
相对于通常的映射方法有序字典还另外提供了逆序迭代的支持通过reversed()。
"""
d = OrderedDict.fromkeys('acbde')
print(d)
print(list(reversed(d)))
c = OrderedDict({'a': 1, 'c': 2, 'b': 3})
print(c)