我有一個像下面這樣的串列
[
[1, 2], [3] 。[4], [5, >6], [7], [8], [9], [10] 。[11, 14], [12, 13] 。
[15], [16], [17] 。[18], [19], [20] 。[21, 61], [22] 。[23], [24], [25] 。
[26, 45], [27] 。[28], [29], [30] 。[31], [32], [33] 。[34], [35, 36] 。
[37], [38], [39] 。[40, 41], [42, 48], [43], [44] 。[46], [47], [49] 。
[50], [51], [52] 。[53], [54, 62] 。[55, 56], [57] 。[58, 59], [60, 61] 。
[63, 62], [64] , [65], [66, 67], [68] , [69]
]
我們可以看到62存在于[54, 62]和[63, 62]中。
我想創建一個新的子串列,將[54, 62]和[63, 62]分組為[54,62,63]。
這樣,我的新串列將如下:
我的新串列將如下:
[
[1, 2], [3] 。[4], [5, >6], [7], [8], [9], [10] 。[11, 14], [12, 13] 。
[15], [16], [17] 。[18], [19], [20] 。[21, 61], [22] 。[23], [24], [25] 。
[26, 45], [27] 。[28], [29], [30] 。[31], [32], [33] 。[34], [35, 36] 。
[37], [38], [39] 。[40, 41], [42, 48], [43], [44] 。[46], [47], [49] 。
[50], [51], [52] 。[53], [54, 62, 63], [55, 56] 。[57], [58, 59] 。
[60, 61], [64] , [65], [66, 67], [68], [69]
]
uj5u.com熱心網友回復:
也許有點矯枉過正,但嘗試從多個方面看問題總是有用的。 如果我們把每個數字看作是一個節點,每個子串列看作是一條邊,那么這個問題就簡化為尋找圖的連接部分。
這可以用networkx輕松完成。
import networkx
from itertools import chain
lst = [
[1, 2], ..., [68], [69]
]
g = networkx.Graph()
g.add_nodes_from(chain.from_iterable(lst))
g.add_edges_from(i for i in lst if len(i)==2)
result = [list(i) for i in networkx.connected_components(g) ]
產生:
[[1, 2],
[3]。
[4]。
[5, 6] 。
[7], ...
[66, 67]。
[68]。
[69]] 。
uj5u.com熱心網友回復:
我最后寫了以下代碼,我認為這對我來說是可行的。
identical_groups=[[1, 2], [5, 6], [11, 14] 。[12, 13], [21, 61] 。[26, 45], [35, 36] 。[40, 41], [42, 48] 。[54, 62], [55, 56] 。[58, 59], [60, 61] 。[63, 62], [66, 67]]
groupedPoints_Dict={}。
index=0]
exist_key=[]
for currentPointGroup in identical_groups:
for point in currentPointGroup:
if len(exist_key)==0:
exist_key = [key for key, value in groupedPoints_Dict.items() if point in value ]
if len(exist_key)>0 :
oldgroupedPoint_List=groupedPoints_Dict[int(''/span>. join(str(e) for e in exist_key)>]
#print "oldgroupedPoint_List", oldgroupedPoint_List)
newgroupedPoint_List=list(set(oldgroupedPoint_List currentPointGroup)
#print "newgroupedPoint_List", newgroupedPoint_List。
#print "existence_key", exist_key
dict_key=int(''.join(str(e) fore in exist_key)
groupedPoints_Dict[dict_key]=newgroupedPoint_List
else:
groupedPoints_Dict[index 1] =currentPointGroup
index = 1] =currentPointGroup
exist_key=[]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/309323.html
標籤:
