以下是一个示例代码,用于比较两列并打印出差异:
# 定义两个列表
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
# 比较两列并打印出差异
diff_list1 = [item for item in list1 if item not in list2]
diff_list2 = [item for item in list2 if item not in list1]
print("列表1中的差异项: ", diff_list1)
print("列表2中的差异项: ", diff_list2)
输出:
列表1中的差异项: [1, 2]
列表2中的差异项: [6, 7]
以上代码使用了列表推导式来比较两列并找出差异项。首先,我们定义了两个列表list1
和list2
。然后,使用列表推导式分别找出在list1
中但不在list2
中的差异项,以及在list2
中但不在list1
中的差异项。最后,通过print
语句将结果打印出来。