获取defaultdict中每个列表的n元素

时间:2018-02-27 19:11:04

标签: python numpy dictionary collections defaultdict

我有一个defaultdict(list)

d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]})

有没有pythonic方法将每个列表中的每个n元素保存到一个新数组中,所以我有这样的东西?:

a = [1,6,11]
b = [2,7,12]
c = [3,8,13]
d = [4,9,14]
e = [5,10,15]

3 个答案:

答案 0 :(得分:2)

以下代码将计算数组nth_el,而nth_el[i]包含所有第i个元素:

d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]})

nth_el = [[d_int[k][i] for k in range(3)] for i in range(5)]

nth_el的价值:

[[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]]

答案 1 :(得分:2)

字典不被视为有序。但是,获得所需输出的一种方法是构造collections.OrderedDict collections.defaultdictzip对象,然后应用一些from collections import OrderedDict, defaultdict d_int = OrderedDict(sorted(defaultdict(list, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]}).items())) dict(enumerate(zip(*d_int.values()))) # {0: (1, 6, 11), 1: (2, 7, 12), 2: (3, 8, 13), 3: (4, 9, 14), 4: (5, 10, 15)} 魔法:

enumerate

此方法的好处是您不必提取字典及其组成列表的长度。此外,ziplocal contextIndex = {{1, batch_size}, {1, source_l*imgH}} local context = context_proto[contextIndex] 都是高效,懒惰的功能。

答案 2 :(得分:1)

示例输出几乎肯定是不切实际的;如果我们有相同类型的数据,请将其放入列表中。这是一个粗略的例子:

>>> d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]})
>>> list(zip(*(v for k,v in sorted(d_int.items()))))
[(1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14), (5, 10, 15)]

步骤如下:items从词典中提取key,value对。 sorted然后按键对它们进行排序,v for k,v in生成器表达式丢弃键,*将值作为单个参数分发到zip转换它们。最后,list从zip对象构建一个列表(可迭代)。