from itertools import permutations, product
def sensitivity_analysis(a,b):
length_a=len(a.keys())
length_b=len(b.keys())
items_a=list(a.keys())
items_b=list(b.keys())
a_variants = [dict(zip(items_a, values))
for values in product((list(p) for p in permutations(items_b)), repeat=length_a)]
b_variants = [dict(zip(items_b, values))
for values in product((list(v) for v in permutations(items_a)), repeat=length_b)]
all_variants = product(a_variants, b_variants)
contains_a=[]
contains_b=[]
for i,j in all_variants:
contains_a.append(i)
contains_b.append(j)
return contains_a,contains_b
def insert_dummies(a,b):
length_a=len(a.keys())
length_b=len(b.keys())
items_a=list(a.keys())
items_b=list(b.keys())
dummy_list=[]
if length_a>length_b:
dummy_number=length_a-length_b
nummer=1
while nummer<dummy_number+1:
dummy_list.append("Dummy%d" %nummer)
nummer=nummer+1
for i in items_a:
f=0
while dummy_number>f:
a.setdefault(i,[]).append(dummy_list[f])
f=f+1
n=0
while n<(dummy_number):
for z in dummy_list:
b[z]=items_a
n=n+1
if length_a<length_b:
dummy_number=length_b-length_a
nummer=1
while nummer<dummy_number+1:
dummy_list.append("Dummy%d" %nummer)
nummer=nummer+1
for i in items_b:
f=0
while dummy_number>f:
b.setdefault(i,[]).append(dummy_list[f])
f=f+1
n=0
while n<(dummy_number):
for z in dummy_list:
a[z]=items_b
n=n+1
else:
return
return a,b
ab={"kart":["marie","alice"],
"vinod":["alice","marie"],
"jordan":["marie","alice"],
"joe":["marie","alice"]}
ba={"alice":["kart","vinod","joe","jordan"],
"marie":["kart","vinod","jordan","joe"]}
thelist1=sensitivity_analysis(ab,ba)[0]
thelist2=sensitivity_analysis(ab,ba)[1]
insert_dummies(thelist1[0],thelist2[0])
我在这里有两个功能。一种是灵敏度分析,它返回两个字典ab和ba的所有可能组合。 insert_dummies函数打算通过添加虚拟变量来使两个字典相乘。例如,上面的词典在添加了虚拟变量后应如下所示。
{'kart': ['marie', 'alice', 'Dummy1', 'Dummy2'],
'vinod': ['alice', 'marie', 'Dummy1', 'Dummy2'],
'jordan': ['marie', 'alice', 'Dummy1', 'Dummy2'],
'joe': ['marie', 'alice', 'Dummy1', 'Dummy2']},
{'alice': ['kart', 'vinod', 'joe', 'jordan'],
'marie': ['kart', 'vinod', 'jordan', 'joe'],
'Dummy1': ['kart', 'vinod', 'jordan', 'joe'],
'Dummy2': ['kart', 'vinod', 'jordan', 'joe']}
但是在这种情况下,对字典ab中的每个键,虚拟1和虚拟2被添加4次。另外,thelist1和thelist2也添加了虚拟变量。我在这里做错了什么?任何帮助表示赞赏!
答案 0 :(得分:0)
问题是我以某种方式创建的字典具有指向同一列表而不是四个相等列表的键。这意味着我更改了单个值,所有其他值似乎也都更改了(实际上,它只是单个对象)。
我已通过更改字典结构以使值具有不同的标识来解决此问题。
newdic1 = {k:v[:] for k, v in list1[i].items()}