首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >合并和联想多个字典

合并和联想多个字典
EN

Stack Overflow用户
提问于 2014-05-09 17:06:22
回答 1查看 106关注 0票数 2

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

代码语言:javascript
运行
复制
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不匹配。最好直接将PicListCondList联系起来。PicList A_nCondList im_aN_a-im_n, A_e-im_a.
EN

回答 1

Stack Overflow用户

发布于 2015-04-15 19:10:54

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

代码语言:javascript
运行
复制
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]

返回的顺序是字典,即

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
cond_list = [im_a] * 2 + [im_n] * 2 + [im_e] * 2

或者,更广泛地说:

代码语言:javascript
运行
复制
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), [])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23570299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档