集合运算。集合a和b中存放着两组文件名的集合,两个集合中有相同的文件名也有不同的文件名,例如 a={"pscores.py","cscores.py","vbscores.py","vfpscores.py","c++scores.py"} b={"pscores.py","dbscores.py","osscores.py","c++scores.py","netscores.py"} (1)求a中存在b中不存在的文件 (2)求a中存在的与b中相同的文件 (3)求两个文件夹中互不相同的文件
时间: 2023-06-09 07:08:44 浏览: 101
好的,针对你的问题,我来给你解答:
1、a中存在b中不存在的文件可以通过求a集合与b集合的差集得到。代码实现如下:
a = {"pscores.py","cscores.py","vbscores.py","vfpscores.py","cscores.py"}
b = {"pscores.py","dbscores.py","osscores.py","cscores.py","netscores.py"}
result = a - b
print(result)
输出结果为:{'vbscores.py', 'vfpscores.py'}
2、a中存在的与b中相同的文件可以通过求a集合与b集合的交集得到。代码实现如下:
a = {"pscores.py","cscores.py","vbscores.py","vfpscores.py","cscores.py"}
b = {"pscores.py","dbscores.py","osscores.py","cscores.py","netscores.py"}
result = a & b
print(result)
输出结果为:{'pscores.py', 'cscores.py'}
3、求两个文件夹中互不相同的文件可以先将两个文件夹中的文件分别放入两个集合中,然后对这两个集合取对称差集即可。代码实现如下:
folder_1 = {"file_1.txt", "file_2.txt", "file_3.txt", "file_4.txt"}
folder_2 = {"file_2.txt", "file_3.txt", "file_5.txt", "file_6.txt"}
set_1 = set(folder_1)
set_2 = set(folder_2)
result = set_1 ^ set_2
print(result)
输出结果为:{'file_5.txt', 'file_6.txt', 'file_1.txt', 'file_4.txt'}
阅读全文