我有两个清单:
list1 = ['1','2','3','4','5','6']
list2 = ['4','5','6','7','8']
现在,我想在list2中查找缺失值和附加值。
输出应为:
Missing value = 1,2,3
Additional Value = 7,8
最佳答案
使用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
关于python - 2个列表中的缺失值和附加值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15529775/