python - 将列表拆分为字典

标签 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)

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

最佳答案

您可以使用 itertools.izip_longest 将列表中的项目分组为等分的 block 。

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 值填充以填充最后一个 block 。

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

关于python - 将列表拆分为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28599559/

相关文章:

python : Convert list of tuple to dict

list - Haskell 在列表和应用函数的列表上迭代每个 2x2 网格

c# - 为什么有两个完全不同版本的 Reverse for List 和 IEnumerable?

java - java.util.List.isEmpty() 是否检查列表本身是否为空?

python - 在 django 查询集中排列键顺序

python - 在单独的 csv 列中写入字典的值并创建标题

python - 无法在 Flask 和 sqlalchemy 中多次导入数据库对象

python - Spark 上下文文本文件 : load multiple files

python - 在Python中加载两个动态库实例

python - 如何获取相同维度的两幅图像中每个像素的MSE