我想將來自不同子串列的常見元素分組并存盤到 python 中的單獨子串列中。
例子:
myList=[ [1,3] , [2,3] , [1,2] , [6,8] , [5,4] , [5,7] , [8,9] ]
outputList=[ [1,2,3] , [6,8,9] , [4,5,7] ]
因為,子串列,[1,3],[2,3] 和 [1,2] 包含公共元素,所以我們為 [1,2,3] 制作了一個單獨的子串列
uj5u.com熱心網友回復:
您可以使用networkx。
import networkx as nx
# You list
myList =[ [1,3] , [2,3] , [1,2] , [6,8] , [5,4] , [5,7] , [8,9] ]
# Generate new graph
new_graph=nx.Graph()
#add your list as the graph edges
new_graph.add_edges_from(myList)
# Get list of sets of the connected components in the graph
outputList = list(nx.connected_components(new_graph))
print(outputList)
[{1, 2, 3}, {8, 9, 6}, {4, 5, 7}]
uj5u.com熱心網友回復:
這是一種不使用外部庫的方法。
def group_by_common_elements(seq):
r = []
for sub in seq:
sub = set(sub)
added = False
for existing in r:
if sub & existing:
existing |= sub
added = True
if not added:
r.append(sub)
return r
print(group_by_common_elements(myList)) # [{1, 2, 3}, {8, 9, 6}, {4, 5, 7}]
如果您的預期輸出(具有公共元素的組數)很長但嵌套串列很短,您可以嘗試通過將每個數字及其對應的組存盤在 dict 中來加快速度。
def group_by_common_elements(seq):
groups_by_number = {}
r = []
for sub in seq:
sub = set(sub)
existing = sub & set(groups_by_number)
if existing:
group = groups_by_number[next(iter(existing))]
group |= sub
for number in sub - existing:
groups_by_number[number] = group
else:
r.append(sub)
for number in sub:
groups_by_number[number] = sub
return r
uj5u.com熱心網友回復:
我不了解您想要子串列的依據是什么。但這里是從串列中獲取所有唯一元素的代碼。og_list=[1,3,4,2,1,3,1,3,3,1,2,3,1,3] unique_list=[] for i in og_list: if i not in unique_list: unique_list.append( i) 或者您可以直接使用串列推導。.ieunique_list=[i for i in og_list if i not in unique_list]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/437630.html
