比较以上 2 个列表的数据并将唯一项仅添加到第 3 个列表
to compare data of above 2 lists & add unique items only to 3rd list
我试过这样获取,但没有成功:
item1 = ['eraser', 'pen', 'pencil', 'ruler']
item2 = ['marker', 'pen', 'sharpner', 'compass', 'eraser']
unique_item = [item for item in item1 if item in item2]
print("Unique items from the list", unique_item)
使用set
并从并集中减去交集:
>>> set_1 = set(['eraser','pen','pencil','ruler'])
>>> set_2 = set(['marker','pen','sharpner','compass','eraser'])
>>> list((set_1 | set_2) - (set_1 & set_2))
['compass', 'marker', 'sharpner', 'ruler', 'pencil']
或使用方法set.symmetric_difference()
:
>>> list(set_1.symmetric_difference(set_2))
['compass', 'ruler', 'pencil', 'marker', 'sharpner']
我试过这样获取,但没有成功:
item1 = ['eraser', 'pen', 'pencil', 'ruler']
item2 = ['marker', 'pen', 'sharpner', 'compass', 'eraser']
unique_item = [item for item in item1 if item in item2]
print("Unique items from the list", unique_item)
使用set
并从并集中减去交集:
>>> set_1 = set(['eraser','pen','pencil','ruler'])
>>> set_2 = set(['marker','pen','sharpner','compass','eraser'])
>>> list((set_1 | set_2) - (set_1 & set_2))
['compass', 'marker', 'sharpner', 'ruler', 'pencil']
或使用方法set.symmetric_difference()
:
>>> list(set_1.symmetric_difference(set_2))
['compass', 'ruler', 'pencil', 'marker', 'sharpner']