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
267 views
in Technique[技术] by (71.8m points)

python - Using sublists to create new lists where numbers don't repeat

Given a list:

g = [[0, 7], 
     [1, 2, 10, 19],
     [3, 4, 5, 6, 15, 21, 24, 27],
     [0, 7, 8, 9, 12, 17],
     [1, 10, 11, 20],
     [8, 12, 13, 18],
     [14, 25],
     [3, 15, 16, 22],
     [9, 13, 17, 18]]

I want to check the numbers in the sublist so that for any number that exists in more than one sublist, both sublists can combine to form a new list, e.g. [8, 12, 13, 18] and [9, 13 ,17, 18] can combine to give [8, 9, 12, 13, 17, 18]. Note: the number doesn't repeat and I want to make the biggest possible list.

I have written the following code, but it is not perfect and repeat has not be eliminated, can anyone help?

for i in g:
    for j in g:
        for k in i:
            for l in j:
                if k  == l:
                    m=list(set(i + j))
                    if m not in n:
                        n.append(m)

My expected output is:

[[0, 7, 8, 9, 12, 13, 17, 18],
 [1, 2, 10, 11, 19, 20],
 [3, 4, 5, 6, 15, 16, 21, 22, 24, 27],
 [25, 14]]
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Starting from your initial list of lists:

>>> g = [[0, 7], 
         [1, 2, 10, 19],
         [3, 4, 5, 6, 15, 21, 24, 27],
         [0, 7, 8, 9, 12, 17],
         [1, 10, 11, 20],
         [8, 12, 13, 18],
         [14, 25],
         [3, 15, 16, 22],
         [9, 13, 17, 18]]

As you work through, I think what you want is to combine all matching sublists in the rest of the list into the current sublist, then remove them from the original list:

>>> for start_index, start in enumerate(g):
    while True:
        for end_index, end in enumerate(g[start_index+1:],
                        start_index+1):
            if any(x == y for x in start for y in end):
                g[start_index].extend(end)
                del g[end_index]
                break
        else:
            break


>>> g
[[0, 7, 0, 7, 8, 9, 12, 17, 8, 12, 13, 18, 9, 13, 17, 18], 
 [1, 2, 10, 19, 1, 10, 11, 20], 

 [3, 4, 5, 6, 15, 21, 24, 27, 3, 15, 16, 22], 
 [14, 25]]

Then all you have to do is get rid of duplicates:

>>> [sorted(set(l)) for l in g]
[[0, 7, 8, 9, 12, 13, 17, 18], 
 [1, 2, 10, 11, 19, 20], 
 [3, 4, 5, 6, 15, 16, 21, 22, 24, 27], 
 [14, 25]]

This is relatively inefficient, but provides you a starting point for enhancement (for example, if start and end were already sets, start & end could replace the any).


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

...