2列表中缺少和附加值

时间:2013-03-20 16:51:22

标签: python

我有两个清单:

list1 = ['1','2','3','4','5','6']
list2 = ['4','5','6','7','8']

现在我想在list2中找到缺失值和附加值。

输出应为:

Missing value = 1,2,3
Additional Value = 7,8

1 个答案:

答案 0 :(得分:16)

使用python sets列出差异:

set(list1).difference(list2)
set(list2).difference(list1)

结果:

>>> print 'Missing values =', ','.join(set(list1).difference(list2))
Missing values = 1,3,2
>>> print 'Additional values =', ','.join(set(list2).difference(list1))
Additional values = 7,8

如果订单很重要,那么你仍然需要使用套装:

set1, set2 = set(list1), set(list2)
[i for i in list1 if i not in set2]
[i for i in list2 if i not in set1]

结果:

>>> print 'Missing values =', ','.join([i for i in list1 if i not in set2])
Missing values = 1,2,3
>>> print 'Missing values =', ','.join([i for i in list2 if i not in set1])
Additional values = 7,8