python学习笔记之两个list之间的差异(差集、交集、并集、查重)

案例1:

list_a = ['1', '2', '3', '4']
list_b = ['1', '2', '3', '5']

# diff
# list_a对应list_b的差集
diff_a_b = set(list_a).difference(set(list_b))
print('list_a对应list_b的差集:', diff_a_b)

# list_b对应list_a的差集
diff_b_a = set(list_b).difference(set(list_a))
print('list_b对应list_a的差集:', diff_b_a)

# intersection
inter = set(list_a).intersection(set(list_b))
print('intersection: ', inter)

# union
union = set(list_a).union(set(list_b))
print('union: ', union)

案例1结果:

list_a对应list_b的差集: {'4'}
list_b对应list_a的差集: {'5'}
intersection:  {'3', '1', '2'}
union:  {'1', '2', '3', '5', '4'}

案例2:

查重时,请引入 from collections import Counter

from collections import Counter

list_c = ['1', '2', '3', '4', '1']
list_dict = dict(Counter(list_c))
print ('Duplicate elements: ', [key for key,value in list_dict.items()if value > 1])
print ('Duplicate elements,repeat times: ', {key:value for key,value in list_dict.items()if value > 1})

案例2结果:

Duplicate elements:  ['1']
Duplicate elements,repeat times:  {'1': 2}

 

你可能感兴趣的:(Python,tools,软件测试)