我不确定我所问的是否可行,但如果是特定应用则会方便.我正在为一个实验建立一个试验列表,其中一个目标可以完全匹配一个素数,或者它可以是一种与目标保持某种关系的特定方式的不匹配.更明确的是,我所有的刺激都属于3级分类,形式如下:
H = {
'A1':{
'B1':{
'C1':[],'C2':[],'C3':[] },
'B2':{
'C1':[],'C2':[],'C3':[] },
'B3':{
'C1':[],'C2':[],'C3':[] }
},
'A2':{
'B1':{
'C1':[],'C2':[],'C3':[] },
'B2':{
'C1':[],'C2':[],'C3':[] },
'B3':{
'C1':[],'C2':[],'C3':[] }
}
}
Run Code Online (Sandbox Code Playgroud)
底部的每个列表中的"树"是一组特定的刺激.如果素数和目标匹配,那很简单.如果他们不这样做,我想从同一B组下的另一个C组中随机抽取而无需替换.
我想要的解决方案是利用(我认为)python如何处理引用并创建一个临时列表,我可以从中弹出()一个刺激.因此,如果试验不一致,并且素数来自H [A1] [B1] [C1],我想从列表中弹出():
tempList = H[A1][B1][C2] + H[A1][B1][C3]
Run Code Online (Sandbox Code Playgroud)
然而,大概是因为我追加了两个列表,在字典中的参考名单被打破,所以如果我删除临时列表中的同上,但没有反映在词典.有没有办法保持参考?谢谢!
编辑:这个玩具示例不能按预期工作:
>>> d = {'A':[1,2,3],'B':[4,5,6]}
>>> l = d['A'] + d['B']
>>> l
[1, 2, 3, 4, 5, 6]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5, 6]
>>> d
{'A': [1, 2, 3], 'B': [4, 5, 6]}
Run Code Online (Sandbox Code Playgroud)
创建一个新的类H以及初始化程序中子列表的路径,并覆盖__*item__()以使基础列表受到影响.
编辑:
一个部分的例子:
class listxer(object):
def __init__(self, structure, paths):
self.structure = structure
self.paths = paths
def _descend(self, path):
return reduce(lambda x,y: x[y], path, self.structure)
def __len__(self):
return sum(len(self._descend(path)) for path in self.paths)
def __getitem__(self, item):
if item < 0:
raise ValueError('negative indices not supported!')
for path in self.paths:
cur = self._descend(path)
if item > len(cur):
item -= len(cur)
continue
else:
return cur[item]
else:
raise IndexError('list index out of range')
H = [[[1, 2], [3, 4, 5]]]
mystruct = listxer(H, ((0, 0), (0, 1)))
print len(mystruct)
print mystruct[3]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |