考虑以下字典 d:
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
我想返回 d 中的前 N 个键:值对(在本例中为 N
不存在“前 n”个键这样的事情,因为dict
不记得首先插入了哪些键。
你可以得到anyn 个键值对:
n_items = take(n, d.items())
这使用了实现take
来自itertools recipes http://docs.python.org/library/itertools.html#recipes:
from itertools import islice
def take(n, iterable):
"""Return the first n items of the iterable as a list."""
return list(islice(iterable, n))
看看它在线工作:ideone http://ideone.com/LLgFX
对于 Python
n_items = take(n, d.iteritems())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)