繁体   English   中英

从两个列表中删除两个集合列表的交集,并将 append 它添加到 python 中的新列表

[英]Remove the intersection of two list of sets from both lists, and append it to a new list in python

我想取集合列表x1,y2的交集,将它们从两个列表中删除,然后将 append 放到一个新列表“res”中。
这是我的代码:(我认为可行)

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'}]

我也从那篇文章中试过这个:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

但是当它是一个集合列表时,这会产生错误:

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'

有没有更好的方法来写这个?
任何帮助或建议将不胜感激。

更新:

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'}]

但是当集合的大小超过一个时:

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'}]

假设 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'}]

我该如何解决?

试试这个,通过使用.intersection()方法。

>>> x1=[{'A'},{'B'},{'c'},{'D'}]
>>> _x1= {e for i in x1 for e in i}     
>>> _x1     
{'c', 'B', 'D', 'A'}
>>> y1=[{'A'},{'B'},{'C'},{'d'}]        
>>> _y1= {e for i in y1 for e in i} 
>>> _y1 
{'d', 'B', 'A', 'C'}
>>> z1 = _x1.intersection(_y1) # intersection   

Output:

>>> [{e} for e in z1]   
[{'B'}, {'A'}]

>>> print(x1,y1)
[{'c'}, {'D'}] [{'C'}, {'d'}]

解释:

  • 转换集合列表以设置并将它们存储到临时变量中,并使用内置 function set( .intersection()提供的 .intersection set()
  • 最后,转换为您需要的格式(即集合列表)

将这些集合列表转换为 freezesets 集合,取交集,然后转换回来:

x1=[{'A'},{'B'},{'c'},{'D'}]
y1=[{'A'},{'B'},{'C'},{'d'}]

def list_of_sets_to_set_of_frozensets(l):
    return set(map(frozenset, l))

def set_of_frozensets_to_list_of_sets(s):
    return list(map(set, s))

res = set_of_frozensets_to_list_of_sets(list_of_sets_to_set_of_frozensets(x1) & list_of_sets_to_set_of_frozensets(y1))

print(x1,y1)
print(res)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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