程序1
list1 = ["CIP00002","CIP00007","CIP00012","CIP00013","CIP00067","CIP00011","CIP00182","CIP00008","CIP00068","CIP00019","CIP00147","CIP00151","CIP00170","CIP00171","CIP00200"]
list2 = ["CIP00002","CIP00003","CIP00004","CIP00007","CIP00008","CIP00009","CIP00011","CIP00012","CIP00013","CIP00014","CIP00015","CIP00016","CIP00017","CIP00018","CIP00019","CIP00020","CIP00021","CIP00022","CIP00023","CIP00024","CIP00027","CIP00033","CIP00040","CIP00041","CIP00042","CIP00043","CIP00045","CIP00053","CIP00055","CIP00056","CIP00057","CIP00063","CIP00064","CIP00065","CIP00066","CIP00067","CIP00068","CIP00069","CIP00070","CIP00071","CIP00072","CIP00073"]
# 找出只存在于list1中的元素
diff1 = [x for x in list1 if x not in list2]
# 找出只存在于list2中的元素
diff2 = [x for x in list2 if x not in list1]
print("只存在于list1中的元素:", diff1, len(diff1))
print("只存在于list2中的元素:", diff2, len(diff2))
运行
$ python3 diff.py
只存在于list1中的元素: ['CIP00182', 'CIP00147', 'CIP00151', 'CIP00170', 'CIP00171', 'CIP00200'] 6
只存在于list2中的元素: ['CIP00003', 'CIP00004', 'CIP00009', 'CIP00014', 'CIP00015', 'CIP00016', 'CIP00017', 'CIP00018', 'CIP00020', 'CIP00021', 'CIP00022', 'CIP00023', 'CIP00024', 'CIP00027', 'CIP00033', 'CIP00040', 'CIP00041', 'CIP00042', 'CIP00043', 'CIP00045', 'CIP00053', 'CIP00055', 'CIP00056', 'CIP00057', 'CIP00063', 'CIP00064', 'CIP00065', 'CIP00066', 'CIP00069', 'CIP00070', 'CIP00071', 'CIP00072', 'CIP00073'] 33
程序2
import re
import sys
def read_file_into_array(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
# 读取整个文件内容
content = file.read()
# 使用正则表达式分割内容,忽略空白字符、逗号、分号、回车和换行符
array = re.split(r'[ ,;\r\n]+', content)
# 过滤掉空字符串
array = [item for item in array if item]
return array
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
return None
def compare(list1, list2):
# 找出只存在于list1中的元素
diff1 = [x for x in list1 if x not in list2]
# 找出只存在于list2中的元素
diff2 = [x for x in list2 if x not in list1]
print("只存在于list1中的元素:", diff1, len(diff1))
print("只存在于list2中的元素:", diff2, len(diff2))
if __name__ == "__main__":
if len(sys.argv) != 3:
print(f"Usage: python {sys.argv[0]} file1 file2")
else:
filename1, filename2 = sys.argv[1], sys.argv[2]
list1 = read_file_into_array(filename1)
list2 = read_file_into_array(filename2)
compare(list1, list2)
运行
lighthouse@VM-20-15-ubuntu:~$ cat data1
aa, bb cc ;dd ,;
lighthouse@VM-20-15-ubuntu:~$ cat data2
cc, , dd, ee, ff, mm,
nn,qq; ,,,,,,;
lighthouse@VM-20-15-ubuntu:~$ python3 diff2.py data1 data2
只存在于list1中的元素: ['aa', 'bb'] 2
只存在于list2中的元素: ['ee', 'ff', 'mm', 'nn', 'qq'] 5