![](/img/trans.png)
[英]list intersection algorithm implementation only using python lists (not sets)
[英]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'}]
解釋:
.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.