将列表拆分为字典

时间:2015-02-19 05:59:29

标签: python list 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)

我只是想知道是否有办法改进代码

1 个答案:

答案 0 :(得分:4)

您可以使用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]}
相关问题