是否有比较列表中项目的功能?
Is there a function to compare items in a list?
有没有办法让我比较两个不同的列表,只去掉相似的?
示例:
list1 = [(JOHN,BLUE,BANANA),(JOHN,BLUE, APPLE),(MARY,PURPLE,GRAPE),(BEN,GREEN,WATERMELON)
list2 = [(JOHN,BLUE),(MARY,PURPLE),(TOMMY,PINK)]
OUTPUT:
[(JOHN, BLUE, BANANA),(JOHN, BLUE, APPLE),(MARY, PURPLE, GRAPE)]
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
a = [JOHN,BLUE,BANANA),(JOHN,BLUE, APPLE),(MARY,PURPLE,GRAPE),(BEN,GREEN,WATERMELON]
b = [(JOHN,BLUE),(MARY,PURPLE),(TOMMY,PINK)]
common_member(a, b)
只需检查 list2
中 list1 中的项目[:2]
list1 = [
('JOHN', 'BLUE', 'BANANA'),
('JOHN', 'BLUE', 'APPLE'),
('MARY', 'PURPLE', 'GRAPE'),
('BEN', 'GREEN', 'WATERMELON'),
]
list2 = [
('JOHN', 'BLUE'),
('MARY', 'PURPLE'),
('TOMMY', 'PINK')]
print([item for item in list1 if item[:2] in list2])
[('JOHN', 'BLUE', 'BANANA'), ('JOHN', 'BLUE', 'APPLE'), ('MARY', 'PURPLE', 'GRAPE')]
您可以尝试以下基本方法:
list1 = [("JOHN","BLUE","BANANA"),("JOHN","BLUE", "APPLE"),("MARY","PURPLE","GRAPE"),("BEN","GREEN","WATERMELON")]
list2 = [("JOHN","BLUE"),("MARY","PURPLE"),("TOMMY","PINK")]
tmp = set()
for i in list1:
for j in list2:
if len(set(i)&set(j)) > 0:
tmp.add(i)
print tmp
结果:
set([('MARY', 'PURPLE', 'GRAPE'), ('JOHN', 'BLUE', 'BANANA'), ('JOHN', 'BLUE', 'APPLE')])
有没有办法让我比较两个不同的列表,只去掉相似的? 示例:
list1 = [(JOHN,BLUE,BANANA),(JOHN,BLUE, APPLE),(MARY,PURPLE,GRAPE),(BEN,GREEN,WATERMELON)
list2 = [(JOHN,BLUE),(MARY,PURPLE),(TOMMY,PINK)]
OUTPUT:
[(JOHN, BLUE, BANANA),(JOHN, BLUE, APPLE),(MARY, PURPLE, GRAPE)]
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
a = [JOHN,BLUE,BANANA),(JOHN,BLUE, APPLE),(MARY,PURPLE,GRAPE),(BEN,GREEN,WATERMELON]
b = [(JOHN,BLUE),(MARY,PURPLE),(TOMMY,PINK)]
common_member(a, b)
只需检查 list2
中 list1 中的项目[:2]list1 = [
('JOHN', 'BLUE', 'BANANA'),
('JOHN', 'BLUE', 'APPLE'),
('MARY', 'PURPLE', 'GRAPE'),
('BEN', 'GREEN', 'WATERMELON'),
]
list2 = [
('JOHN', 'BLUE'),
('MARY', 'PURPLE'),
('TOMMY', 'PINK')]
print([item for item in list1 if item[:2] in list2])
[('JOHN', 'BLUE', 'BANANA'), ('JOHN', 'BLUE', 'APPLE'), ('MARY', 'PURPLE', 'GRAPE')]
您可以尝试以下基本方法:
list1 = [("JOHN","BLUE","BANANA"),("JOHN","BLUE", "APPLE"),("MARY","PURPLE","GRAPE"),("BEN","GREEN","WATERMELON")]
list2 = [("JOHN","BLUE"),("MARY","PURPLE"),("TOMMY","PINK")]
tmp = set()
for i in list1:
for j in list2:
if len(set(i)&set(j)) > 0:
tmp.add(i)
print tmp
结果:
set([('MARY', 'PURPLE', 'GRAPE'), ('JOHN', 'BLUE', 'BANANA'), ('JOHN', 'BLUE', 'APPLE')])