Created
February 27, 2018 07:42
-
-
Save vimiix/2a77a3608dc80759ef9d9fefaa2e1369 to your computer and use it in GitHub Desktop.
从有序字典中获取第一个元素的方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
od = OrderedDict(zip('foo', 'bar')) | |
# 方法1 | |
od.keys()[-1] # 仅适用于2 | |
od.values()[-1] | |
od.items()[-1] | |
list(od.items())[-1] # 兼容 3.x | |
# 方法2 | |
od.popitem() # 这会修改掉元数据本身 | |
# 方法3 | |
next(reversed(od)) # 获取最后一个 key | |
next(reversed(od.items())) # 获取最后一个 item | |
next(iter(od)) # 获取第一个 key | |
next(iter(od.items())) # 获取第一个 item |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment