组合和关联多个词典 [英] Combining and associating multiple dictionaries
本文介绍了组合和关联多个词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成一个字典,其中组织了三个不同图片组的六个不同组合.那就是为什么我计算字典的原因:
I want to generate a dictionary in which six different combination of three different groups of pictures are organized. Thats why I computed a 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})
这时有两个问题:
- 首先,有没有更好的方法来合并两个图片列表和第二个
- 如果我以此方式组织字典,则
CondList
与PicList
不匹配.将PicList
直接关联到CondList
会很好.其中PicList
A_n
与CondList
im_a
和N_a-im_n, A_e-im_a
... 相关联
- First, is there a better way to combine the two Lists of pictures and second
- If I organize a dictionary in this way,
CondList
doesn't match withPicList
. It would be nice to associatePicList
directly toCondList
. WherePicList
A_n
is associated withCondList
im_a
andN_a-im_n, A_e-im_a
...
推荐答案
To answer the first point, you can use 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]
返回的命令是按字母顺序排列的,即
The order returned is lexicographic, i.e.
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
:
The respective cond_list
can be built by simply doing:
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), [])
这篇关于组合和关联多个词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文