Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在列表中拆分dict_Python_List_Dictionary - Fatal编程技术网

Python:在列表中拆分dict

Python:在列表中拆分dict,python,list,dictionary,Python,List,Dictionary,我想把这样一个简单的dict:d={0:0,1:1,2:2,3:3}转换成一个dict列表,每个dict中的元素数量(大约)与下面的dict相同:[{0:0,2:2},{1:1,3:3}]。我尝试过简单的索引,就像我在列表中使用的那样,但它给我带来了一个TypeError:unhabable类型:“slice”。这就是我现在所拥有的: def dico_chunks(dico, n): if len(dico) < n: n = len(dico) retu

我想把这样一个简单的dict:
d={0:0,1:1,2:2,3:3}
转换成一个dict列表,每个dict中的元素数量(大约)与下面的dict相同:
[{0:0,2:2},{1:1,3:3}]
。我尝试过简单的索引,就像我在列表中使用的那样,但它给我带来了一个
TypeError:unhabable类型:“slice”
。这就是我现在所拥有的:

def dico_chunks(dico, n):
    if len(dico) < n:
        n = len(dico)
    return [dico[i::n] for i in range(n)]
def dico_块(dico,n):
如果len(dico)

请记住,无论如何,我都不需要对列表进行排序。我只需要将我的主目录拆分成一个
n
子目录列表

您可以使用中定义的
pairwise
函数执行此操作,将dict的
items()
传递给它:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

d = {0:0, 1:1, 2:2, 3:3}

list(map(dict,pairwise(d.items())))
# [{0: 0, 1: 1}, {1: 1, 2: 2}, {2: 2, 3: 3}]
如果需要非重复对,则可以使用
zip

items = list(d.items())

list(map(dict, zip(items[::2], items[1::2])))
# [{0: 0, 1: 1}, {2: 2, 3: 3}]

字典基本上是无序的,因此如果您想要特定的顺序,则需要使用其他逻辑来指定该顺序。

基于生成器的方法:

def chunk_dict(d, chunk_size):
    r = {}
    for k, v in d.items():
        if len(r) == chunk_size:
            yield r
            r = {}
        r[k] = v
    if r:
        yield r

d = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
list(chunk_dict(d, 2))
# [{1: 1, 2: 2}, {3: 3, 4: 4}, {5: 5, 6: 6}]
相同功能的更短、更高性能版本(使用
itertools.islice
) 可以在中找到

对于给定数量的尽可能均匀分布的块(例如大小为4、4、3、3而不是4、4、4、2),您可以执行以下操作:

chunks = [{} for _ in range(num_chunks)]
for i, k in enumerate(d):
    chunks[i % num_chunks][k] = d[v]

您需要决定将哪些元素放入列表中的同一词典中的规则。词典是无序集合,这些项没有与之关联的自然索引号。您可以拆分dict的键列表,但请记住,该列表可能不是您期望的顺序。您可以更清楚地制定拆分规则吗?我需要主dict中的每个值在任何子dict中只出现一次。我只需要将主dict拆分为多个较小的dict(
n
)每个子指令中的值数量相同。链接问题中的已接受答案是否符合您的要求?我接收的不是
chunk\u size
arg,而是
number\u of chunk
,它决定了chunk size本身。
chunk\u size=len(d)//num\u chunks
或类似选项将让您从一个到另一个。FWIW,我打算发布这样的帖子:
items=sorted(dico.items())
n=min(n,len(dico))
return[dict(items[I::n])for I in range(n)]
…@Marc AntoineGiguère您可能想玩玩我刚才在前面的评论中输入的代码。@PM2Ring Yup,这是更聪明(可能更神秘)的版本:)