I want to take the intersection of the list of sets x1,y2
, remove them from both lists, then append it to a new list 'res'.
This is my code: (which works I think)
x1=[{'A'},{'B'},{'c'},{'D'}]
y1=[{'A'},{'B'},{'C'},{'d'}]
res=[]
for i in x1:
if i in y1:
res.append(i)
x1.remove(i)
y1.remove(i)
for i in y1:
if i in x1:
res.append(i)
x1.remove(i)
y1.remove(i)
print(x1,y1)
>[{'c'}, {'D'}] [{'C'}, {'d'}]
print(res)
>[{'A'}, {'B'}]
I also tried this from that post:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
But when it's a list of sets, this gives errors:
x1=[{'A'},{'B'},{'c'},{'D'}]
y1=[{'A'},{'B'},{'C'},{'d'}]
res=[]
res.append(list(set(x1) & set(x2)))
print(x1,y1)
print(res)
>TypeError: unhashable type: 'set'
Is there any better methods to write this ?
Any help or suggestion would be appreciated.
Update:
x1=[{'A'},{'B'},{'c'},{'D'}]
y1=[{'A'},{'B'},{'C'},{'d'}]
x2= {e for i in x1 for e in i}
y2= {e for i in y1 for e in i}
z1 = x2.intersection(y2)
res = [{e} for e in z1]
x1=[{e} for e in x2-z1]
y1=[{e} for e in y2-z1]
print(x1,y1)
>[{'c'}, {'D'}] [{'C'}, {'d'}]
print(res)
>[{'A'}, {'B'}]
But when the set have size more then one:
x1=[{'A','B'},{'B'},{'c'},{'D'}]
y1=[{'A'},{'B'},{'C'},{'d'}]
x2= {e for i in x1 for e in i}
y2= {e for i in y1 for e in i}
z1 = x2.intersection(y2)
res = [{e} for e in z1]
x1=[{e} for e in x2-z1]
y1=[{e} for e in y2-z1]
print(x1,y1)
>[{'D'}, {'c'}] [{'C'}, {'d'}]
print(res)
>[{'B'}, {'A'}]
Which suppose output:
x1=[{'A','B'},{'B'},{'c'},{'D'}]
y1=[{'A'},{'B'},{'C'},{'d'}]
res=[]
for i in x1:
if i in y1:
res.append(i)
x1.remove(i)
y1.remove(i)
for i in y1:
if i in x1:
res.append(i)
x1.remove(i)
y1.remove(i)
print(x1,y1)
>[{'B', 'A'}, {'c'}, {'D'}] [{'A'}, {'C'}, {'d'}]
print(res)
[{'B'}]
How do I fix this?