添付したコードのようにリストのリストがあります。共通の値があれば、各サブリストをリンクしたい。次に、リストのリストをリストの要約リストに置き換えたいと思います。例:[[1,2,3],[3,4]]
欲しい リストがあるとし[1,2,3,4]
ます。あるなら[[4,3],[1,2,3]]
欲しい[4,3,1,2]
。私が持っているなら、私は[[1,2,3],[a,b],[3,4],[b,c]]
欲しい[[1,2,3,4],[a,b,c]]
か、どちらか[[a,b,c],[1,2,3,4]]
は気にしません。
私はほとんどそこにいます...
[[1,2,3],[10,5],[3,8,5]]
私の問題は、私が望むようなケースがある[1,2,3,10,5,8]
が、現在のコードで私が得たときです[1,2,3,8,10,5]
これが私のコードです:
import itertools
a = [1,2,3]
b = [3,4]
i = [21,22]
c = [88,7,8]
e = [5,4]
d = [3, 50]
f = [8,9]
g= [9,10]
h = [20,21]
lst = [a,b,c,i,e,d,f,g,h,a,c,i]*1000
#I have a lot of list but not very many different lists
def any_overlap(a, b):
sb = set(b)
return any(itertools.imap(sb.__contains__, a))
def find_uniq(lst):
''' return the uniq parts of lst'''
seen = set()
seen_add = seen.add
return [ x for x in lst if x not in seen and not seen_add(x)]
def overlap_inlist(o_lst, lstoflst):
'''
Search for overlap, using "any_overlap", of a list( o_lst) in a list of lists (lstoflst).
If there is overlap add the uniq part of the found list to the search list, and keep
track of where that list was found
'''
used_lst =[ ]
n_lst =[ ]
for lst_num, each_lst in enumerate(lstoflst):
if any_overlap(o_lst,each_lst):
n_lst.extend(each_lst)
used_lst.append(lst_num)
n_lst= find_uniq(n_lst)
return n_lst, used_lst
def comb_list(lst):
'''
For each list in a list of list find all the overlaps using 'ovelap_inlist'.
Update the list each time to delete the found lists. Return the final combined list.
'''
for updated_lst in lst:
n_lst, used_lst = overlap_inlist(updated_lst,lst)
lst[:] = [x for i,x in enumerate(lst) if i not in used_lst]
lst.insert(0,n_lst)
return lst
comb_lst = comb_list(lst)
print comb_lst
このスクリプトの出力は次のとおりです。
[[88, 7, 8, 9, 10], [1, 2, 3, 4, 50, 5], [21, 22, 20]]
キーが次のような元の順序になるようにします。
[[88, 7, 8, 9, 10], [1, 2, 3, 4, 5, 50,], [21, 22, 20]]
5 と 50 は新しい lst[2] で切り替えられます
私はPythonに少し慣れていません。問題の解決策や現在のコードに関するコメントをいただければ幸いです。私はコンピューター科学者ではありませんが、これを迅速に行うある種のアルゴリズムが存在する可能性があると思います (おそらく集合論から?)。そのようなアルゴリズムがある場合は、正しい方向に向けてください。
私はこの方法をもっと複雑にしているかもしれません...ありがとう!!