python 笛卡尔积_字典键和值Python的笛卡尔积

I have two lists with data:

COURSES = [C1, C2, C3]

ROOMS = [R1, R2, R3]

and I already created a list of tuples containing their cartesian product:

L_CR = list(itertools.product(COURSES, ROOMS))

#print(L_CR): [('C1', 'R1'), ('C1', 'R2'), ('C1', 'R3'), ('C2', 'R1').....

Now I have created two dictionaries storing integer values about the amount of people attending a course and the maximum amount of people fitting into a room:

dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}

dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}

What I can't figure out is how I can create a dictionary which has the tuples as keys and the absolut difference between the maximum amount of people possible for a room and the number of people attending a course.

What I did so far was creating a dictionary which stores each tuple as a key and where each key gets assigned a value of 1:

Dic_Courses_Room_Capacity = {}

for Element in L_CR:

Dic_Courses_Room_Capacity_Temp = {Element: 1}

Dic_Courses_Room_Capacity.update(Dic_Students_Room_Capacity_Temp)

Which results in:

#print(Dic_Courses_Room_Capacity): {('C1', 'R1'): 1, ('C1', 'R2'): 1, ('C1', 'R3'): 1...

But what I am looking for would be:

#print(Dic_Courses_Room_Capacity): {('C1', 'R1'): 5 , ('C1', 'R2'): 0, ('C1', 'R3'): 10

where e.g.: ('C1', 'R3'): 10 = abs('C1' -'R3') = abs(10-20) = abs(-10) = 10

So I have to update my existing dictionary (Dic_Courses_Room_Capacity) with all calculated combinations of the other two dictionaries. I tried to loop through those two dictionaries with two for loops but that resulted in always getting the same number for each key(=tuple).

Any ideas?

Best regards,

Jan

解决方案

Simple iteration through two dictionaries, adding tuple and absolute difference to another:

dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}

dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}

d = {}

for k1, v1 in dic_courses.items():

for k2, v2 in dic_rooms.items():

d.update({(k1, k2): abs(v1 - v2)})

print(d)

# {('C1', 'R1'): 5, ('C1', 'R2'): 0, ('C1', 'R3'): 10,

# ('C2', 'R1'): 0, ('C2', 'R2'): 5, ('C2', 'R3'): 15,

# ('C3', 'R1'): 15, ('C3', 'R2'): 10, ('C3', 'R3'): 0}

Or itertools.product way:

from itertools import product

dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}

dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}

d = {}

for x, y in product(dic_courses, dic_rooms):

d.update({(x, y): abs(dic_courses[x] - dic_rooms[y])})

print(d)

# {('C1', 'R1'): 5, ('C1', 'R2'): 0, ('C1', 'R3'): 10,

# ('C2', 'R1'): 0, ('C2', 'R2'): 5, ('C2', 'R3'): 15,

# ('C3', 'R1'): 15, ('C3', 'R2'): 10, ('C3', 'R3'): 0}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值