實(shí)現(xiàn)一個(gè)類似PHP的array_chunk函數(shù)的功能
def dict_chunk(dicts,size):
new_list = []
dict_len = len(dicts)
# 獲取分組數(shù)
while_count = dict_len // size + 1 if dict_len % size != 0 else dict_len / size
split_start = 0
split_end = size
while(while_count > 0):
# 把字典的鍵放到列表中学歧,然后根據(jù)偏移量拆分字典
new_list.append({k: dicts[k] for k in list(dicts.keys())[split_start:split_end]})
split_start += size
split_end += size
while_count -= 1
return new_list
例子:
phones = {
'a_01':'1200x1500',
'a_02':'1280x1480',
'a_03':'1220x1520',
'a_04':'1240x1540',
'a_05':'1240x1540',
'a_06':'1220x1520',
'a_07':'1240x1540',
'a_08':'1200x1500',
'a_09':'1240x1540',
'a_10':'1240x1540',
'a_11':'1280x1480',
'a_12':'1240x1540',
'a_13':'1220x1520',
'a_14':'1200x1500',
'a_15':'1280x1480',
'a_16':'1240x1540',
'a_17':'1200x1500',
'a_18':'1280x1480',
'a_19':'1240x1540',
'a_20':'1280x1480',
'a_21':'1240x1540',
'a_22':'1280x1480',
}
res = dict_chunk(phones,10)
print(res)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------[{'a_01': '1200x1500', 'a_02': '1280x1480', 'a_03': '1220x1520', 'a_04': '1240x1540', 'a_05': '1240x1540', 'a_06': '1220x1520', 'a_07': '1240x1540', 'a_08': '1200x1500', 'a_09': '1240x1540', 'a_10': '1240x1540'}, {'a_11': '1280x1480', 'a_12': '1240x1540', 'a_13': '1220x1520', 'a_14': '1200x1500', 'a_15': '1280x1480', 'a_16': '1240x1540', 'a_17': '1200x1500', 'a_18': '1280x1480', 'a_19': '1240x1540', 'a_20': '1280x1480'}, {'a_21': '1240x1540', 'a_22': '1280x1480'}]