将列表拆分为字典

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]}