简体   繁体   中英

Find similar items in list of lists using Python

I'm trying to do something similar to this link , but using lists of lists. Doing the following, however, gives me a TypeError.

list1 = [[a,a], [b,b], [c,c]]
list2 = [[c,c], [d,d], [e,e]]

same = set(list1) & set(list2)

I'm also trying to find:

different = not set(list1) & set(list2)

Lists are not hashable types, so they can't be put into sets, but tuples can. You can convert a list to a tuple with tuple(mylist) . The following code assumes that a,b,c,d and e are hashable types.

list1 = [(a,a), (b,b), (c,c)]
list2 = [(c,c), (d,d), (e,e)]

same = set(list1) & set(list2)

It would be more readable and more understandable if you just used list comprehension like so ..

def seperate(*ls):
   sim, diff = []
   for l in ls:
       sim.extend([ x for x in l if x not in sim ])
       diff.extend([ x for x in l if x not in sim ])
   return sim, diff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM