我有一个包含数千个元素的非常大的字典。我需要用这个字典作为参数执行一个函数。现在,我不想在一次执行中传递整个字典,而是想分批执行该函数 - 一次使用字典的 x 个键值对。
我正在做以下事情:
mydict = ##some large hash
x = ##batch size
def some_func(data):
##do something on data
temp = {}
for key,value in mydict.iteritems():
if len(temp) != 0 and len(temp)%x == 0:
some_func(temp)
temp = {}
temp[key] = value
else:
temp[key] = value
if temp != {}:
some_func(temp)
这对我来说看起来很骇人听闻。我想知道是否有一种优雅/更好的方法来做到这一点。
最佳答案
我经常使用这个小工具:
import itertools
def chunked(it, size):
it = iter(it)
while True:
p = tuple(itertools.islice(it, size))
if not p:
break
yield p
对于您的用例:
for chunk in chunked(big_dict.iteritems(), batch_size):
func(chunk)
关于python - 如何遍历字典——一次 n 个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28022223/