[英]Split list into dictionary
我試圖將列表拆分成字典,並為此編寫了一個函數。 它接受一個列表並獲取列表長度。 如果列表的長度為253,它將創建一個包含26個鍵的字典-通過將數字四舍五入到更高的10位來計算(250將創建25個鍵,251-259將創建26個鍵)。 每個鍵將存儲原始列表的卡盤(截至目前,每個列表存儲10個元素)。 我覺得
def limit_files(file_list, at_a_time=10):
l = file_list
n = len(l)
d, r = divmod(n, at_a_time)
num_keys = d + 1 if r else d
slice = n // num_keys
vals = (l[i:i+slice] for i in range(0, n, slice+1))
dct = dict(zip(range(1,num_keys+1),vals))
return (dct)
我只是想知道是否有改進代碼的方法
您可以使用itertools.izip_longest
將列表中的項目分組為均等的塊。
import itertools
def limit_files(file_list, at_a_time=10):
d, r = divmod(len(file_list), at_a_time)
num_keys = d + 1 if r > 0 else d
chunks = itertools.izip_longest(*([iter(x)] * at_a_time))
return dict((x, y) for x, y in enumerate(chunks))
注意,將使用None
值填充以填充最后一個塊。
>>> limit_files([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
{0: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
1: (11, 12, None, None, None, None, None, None, None, None)}
另外,也可以不使用填充值,而僅遍歷范圍並調用itertools.islice
直到迭代器耗盡為止,如下所示:
def limit_files(file_list, at_a_time=10):
d, r = divmod(len(file_list), at_a_time)
num_keys = d + 1 if r > 0 else d
iterator = iter(file_list)
dictionary = {}
for chunk_id in xrange(num_keys):
chunk = list(itertools.islice(iterator, at_a_time))
if not chunk:
break
dictionary[chunk_id] = chunk
return dictionary
>>> limit_files([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
{0: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1: [11, 12]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.