[英]Merging sets within sets in Python
我有一個像這樣的集合(任何集合類型都可以滿足我的要求)。
myset = {{a},{b},{c},{d,e}, {d,f}}
我現在正在嘗試檢查兩個元素 {a} 和 {d} 是否存在於 myset 中,如果存在則將 {a} 與 {d,e} 合並。 另一方面,如果我正在檢查 {d} 和 {f},那么我將合並 {d,e} 和 {d,f} 以獲得 {d,e,f}。
如果有人向我展示解決方案的方向,我將不勝感激。
這可能不是最pythonic的方法,但它應該可以工作,請讓我知道是否可以,並且我已經完成了對列表的操作,可以使用類似的方法對集合進行操作
def get_member(a,the_list):
if a in the_list:
return a
else:
for elem in the_list:
if isinstance(elem,list):
if a in elem:
return elem
return None
def merge_member(a,b,the_list):
get_member_a = get_member(a,the_list)
get_member_b = get_member(b,the_list)
if get_member_a and get_member_b:
the_list.remove(get_member_a)
the_list.remove(get_member_b)
if isinstance(get_member_b,list):
get_member_b.extend(get_member_a)
the_list.append(get_member_b)
elif isinstance(get_member_a,list):
get_member_a.extend(get_member_b)
the_list.append(get_member_a)
else:
the_list.append([get_member_b,get_member_a])
return the_list
首先:您不能在 python 中構建一組集合,因為set
需要包含可哈希值,而set
本身不可哈希。
但是當然你可以對集合列表做同樣的事情。 可能最快和最 pythonic 的解決方案應該是這樣的:
myset = [{1}, {2}, {3}, {4, 5}, {5, 6}]
merged_set = set().union(*myset)
(set.union 不能只和一個參數一起使用,可以和任意多個參數一起使用)
我似乎需要改進merge_member塊,以處理具有[['a'],['b'],['c'],['d'],['e','f' ,'g']],作為the_list,我們正在尋找'e'和'f'。
def merge_member(a,b,the_list):
get_member_a = get_member(a, the_list)
get_member_b = get_member(b, the_list)
if get_member_a and get_member_b:
if get_member_a.__eq__(get_member_b):
the_list.remove(get_member_a)
if isinstance(get_member_b, list):
the_list.append(get_member_b)
else:
the_list.remove(get_member_a)
the_list.remove(get_member_b)
if isinstance(get_member_b, list):
get_member_b.extend(get_member_a)
the_list.append(get_member_b)
elif isinstance(get_member_a, list):
get_member_a.extend(get_member_b)
the_list.append(get_member_a)
else:
the_list.append([get_member_b,get_member_a])
return the_list
您可以使用此方法合並設置列表:
from functools import reduce # for python3
myset = [{'a'}, {'b'}, {'c'}, {'d','e'}, {'d','f'}]
reduce(lambda x, y: {*x, *y}, myset)
輸出:
{'a', 'b', 'c', 'd', 'e', 'f'}
問題的解決方案:
from functools import reduce # for python3
myset = [{'a'}, {'b'}, {'c'}, {'d','e'}, {'d','f'}] # define your set list
def get_element_set(elem, myset):
try:
z = [x for x in myset if elem in x]
result = reduce(lambda x, y: {*x, *y}, z)
return result
except TypeError as e:
print('Element "%s" is not exist in myset!' % elem)
return {}
def merge_member(elem_list, myset):
z = map(lambda elem: get_element_set(elem, myset), elem_list)
result = reduce(lambda x, y: {*x, *y}, z)
return result
例:
get_element_set('d', myset) # {'d', 'e', 'f'}
get_element_set('g', myset) # Element "g" is not exist in myset! {}
merge_member(['f', 'd'], myset) # {'d', 'e', 'f'}
merge_member(['a', 'd'], myset) # {'a', 'd', 'e', 'f'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.