/ 猿问

# 合并具有共同元素的列表

2019-11-14 15:20:23

L = [['a','b','c'],['b','d','e'],['k'],['o','p'],['e','f'],['p','a'],['d','g']]

L = [['a','b','c','d','e','f','g','o','p'],['k']]

## 3 回答

l = [['a','b','c'],['b','d','e'],['k'],['o','p'],['e','f'],['p','a'],['d','g']]

import networkx

from networkx.algorithms.components.connected import connected_components

def to_graph(l):

G = networkx.Graph()

for part in l:

# each sublist is a bunch of nodes

# it also imlies a number of edges:

return G

def to_edges(l):

"""

treat `l` as a Graph and returns it's edges

to_edges(['a','b','c','d']) -> [(a,b), (b,c),(c,d)]

"""

it = iter(l)

last = next(it)

for current in it:

yield last, current

last = current

G = to_graph(l)

print connected_components(G)

# prints [['a', 'c', 'b', 'e', 'd', 'g', 'f', 'o', 'p'], ['k']]

l = [['a', 'b', 'c'], ['b', 'd', 'e'], ['k'], ['o', 'p'], ['e', 'f'], ['p', 'a'], ['d', 'g']]

out = []

while len(l)>0:

first, *rest = l

first = set(first)

lf = -1

while len(first)>lf:

lf = len(first)

rest2 = []

for r in rest:

if len(first.intersection(set(r)))>0:

first |= set(r)

else:

rest2.append(r)

rest = rest2

out.append(first)

l = rest

print(out)

lists = [['a','b','c'],['b','d','e'],['k'],['o','p'],['e','f'],['p','a'],['d','g']]

lists = sorted([sorted(x) for x in lists]) #Sorts lists in place so you dont miss things. Trust me, needs to be done.

resultslist = [] #Create the empty result list.

if len(lists) >= 1: # If your list is empty then you dont need to do anything.

if len(lists) > 1: #If there is only one list in your list then you dont need to do anything.

for l in lists[1:]: #Loop through lists starting at list 1

listset = set(l) #Turn you list into a set

merged = False #Trigger

for index in range(len(resultlist)): #Use indexes of the list for speed.

rset = set(resultlist[index]) #Get list from you resultset as a set

if len(listset & rset) != 0: #If listset and rset have a common value then the len will be greater than 1

resultlist[index] = list(listset | rset) #Update the resultlist with the updated union of listset and rset

merged = True #Turn trigger to True

break #Because you found a match there is no need to continue the for loop.

if not merged: #If there was no match then add the list to the resultset, so it doesnt get left out.

resultlist.append(l)

print resultlist

resultset = [['a', 'b', 'c', 'd', 'e', 'g', 'f', 'o', 'p'], ['k']]

• 3 回答
• 0 关注
• 92 浏览

0/150