组合和关联多个词典

时间:2014-05-09 17:06:23

标签: python dictionary

我想生成一个字典,其中组织了三组不同图片的六种不同组合。这就是我计算字典的原因:

import glob, os, random, sys, time
import numpy.random as rnd

im_a = glob.glob('./a*')   # upload pictures of the a-type, gives out a List of .jpg-files
im_n = glob.glob('./n*')   # n-type
im_e = glob.glob('./e*')   # e-type

# combining Lists of Pictures
A_n = im_a + im_n
N_a = im_n + im_a
A_e = im_a + im_e
E_a = im_e + im_a
E_n = im_e + im_n
N_e = im_n + im_e

# making a Dictionary of Pictures and Conditions
PicList = [A_n, N_a, A_e, E_a, E_n, N_e]   # just the six Combinations
CondList = [im_a,im_n,im_a,im_e,im_e,im_n] # images that are in the GO-Condition
ImageList = []
ImageList.append({'PicList':PicList, 'CondList':CondList})

目前有两个问题:

  1. 首先,是否有更好的方法来合并两个图片列表和第二个
  2. 如果我以这种方式整理字典,CondListPicList不符。将PicList直接关联到CondList会很高兴。 PicList A_nCondList im_aN_a-im_n, A_e-im_a ...
  3. 相关联的位置

1 个答案:

答案 0 :(得分:0)

要回答第一点,您可以使用itertools.permutations

import itertools as it

elements = [im_a, im_n, im_e]
perms = it.permutations(elements, 2)    # 2 -> take pairs
pic_list = [sum(perm, []) for perm in perms]

返回的顺序是词典,即

im_a + im_n, im_a + im_e, im_n + im_a, im_n + im_e, im_e + im_a, im_e + im_n

只需执行以下操作即可构建相应的cond_list

cond_list = [im_a] * 2 + [im_n] * 2 + [im_e] * 2

或者,更一般地说:

d = len(elements) - 1
cond_list = list(chain.from_iterable([el]*d for el in elements))
# or
cond_list = sum(([el]*d for el in elements), [])