表1和表2是两组商品的名称和价格,编写Python程序并使用集合完成下列任务: (1)输出两表均包含的商品信息; (2)输出属于表1但不属于表2的商品信息; (3)输出属于表1但不属于表2,或者属于表2但不属于表1的商品信息; (4)输入商品名称,查询其价格。
时间: 2024-06-10 13:04:33 浏览: 6
ChitGPT: 好的,我已经记录下来了。让我思考一下如何回答您的问题。
以下是使用Python程序完成这些任务的代码:
```python
table1 = {"Product A": 10, "Product B": 20, "Product C": 30}
table2 = {"Product A": 10, "Product D": 40, "Product E": 50}
# (1) 输出两表均包含的商品信息
intersection = set(table1.keys()) & set(table2.keys())
print("商品信息同时出现在表1和表2中:", intersection)
# (2) 输出属于表1但不属于表2的商品信息
difference = set(table1.keys()) - set(table2.keys())
print("属于表1但不属于表2的商品信息:", difference)
# (3) 输出属于表1但不属于表2,或者属于表2但不属于表1的商品信息
symmetric_difference = set(table1.keys()) ^ set(table2.keys())
print("属于表1或表2但不属于两表中都出现过的商品信息:", symmetric_difference)
# (4) 输入商品名称,查询其价格
product_name = input("请输入要查询的商品名称:")
if product_name in table1.keys():
print(product_name, "在表1中的价格为:", table1[product_name])
elif product_name in table2.keys():
print(product_name, "在表2中的价格为:", table2[product_name])
else:
print("该商品名称不存在于两个表中,请重新输入。")
```
ChitGPT: 以上代码应该能够帮助您完成任务。如果您还有其他问题,可以继续提出。