Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

list - python about linking sublist with same number together

I need to group sublists with the same elements together For example:

list1 =[[1, 0], [2, 1], [30, 32]]

would link [1, 0] and [2, 1] together since they both contain 1 and those two would combine into [0, 1, 2]

So after linking, the new list should be like:

new_list1 = [[1, 0, 2], [30, 32]]

IE: there shouldn't be same number inside a sub-list and order is not important.

A longer example:

list2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]

after linking, it would be

new_list2 = [[2, 3, 4], [6, 5, 7, 8], [13, 14], [30, 32]]

So how can this be done in a general way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To group the sublists in a general way you can:

Code:

def linking_sublists(lists):
    index = {}
    sets = []
    for l in lists:
        found = None
        for i in l:
            if i in index:
                # this list has an element we have already seen
                if found:
                    # combine two sets
                    to_remove = index[i]
                    if found != to_remove:
                        for j in index[i]:
                            found.add(j)
                            index[j] = found
                        to_remove.clear()
                else:
                    found = index[i]

        if found is not None:
            s = found
            for i in l:
                s.add(i)
        else:
            s = set(l)
            sets.append(s)
        for i in l:
            index[i] = s

    return [list(sorted(s)) for s in sets if s]

How:

This function uses sets and an index dict to group any list with matching elements into sets and track which elements are already in a set.

Test Code:

list_2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]
print(linking_sublists(list_2))

list_3 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [30, 32], [4, 5], [3, 4]]
print(linking_sublists(list_3))

Results:

[[2, 3, 4], [5, 6, 7, 8], [13, 14], [30, 32]]
[[2, 3, 4, 5, 6, 7, 8], [30, 32]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...