How to merge lists with common elements in a list of lists?How to merge two dictionaries in a single expression?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat does the “yield” keyword do?What is the difference between Python's list methods append and extend?How to make a flat list out of list of listsHow do you read from stdin?How do I get the number of elements in a list?How to clone or copy a list?How do I list all files of a directory?

What happens to unproductive professors?

How are mathematicians paid to do research?

Would a non-attacking Barbarian's rage end the same turn he started it?

Why did Harry Potter get a bedroom?

How to know if blackberries are safe to eat?

What is this little owl-like bird?

The tensor product of two monoidal categories

How do we handle pauses in a dialogue?

Why didn't Thanos kill all the Dwarves on Nidavellir?

Are there any medieval light sources without fire?

Addressing unnecessary daily meetings with manager?

Single word for "refusing to move to next activity unless present one is completed."

Why is the air gap between the stator and rotor on a motor kept as small as it is?

Is there a strong legal guarantee that the U.S. can give to another country that it won't attack them?

How to befriend private nested class

Why does wrapping aluminium foil around my food help it keep warm, even though aluminium is a good conductor?

When an electron changes its spin, or any other intrinsic property, is it still the same electron?

Can I run a #12 outlet branch and a #14 light branch off a 30A breaker?

What is a "shilicashe?"

Can you cast a blanket Invisibility and let the targets see each other?

Shortest hex dumping program

RPI3B+: What are the four components below the HDMI connector called?

Is "De qui parles-tu" (for example) as formal as it is in English, or is it normal for the French to casually say that

Why does this potentiometer in an op-amp feedback path cause noise when adjusted?



How to merge lists with common elements in a list of lists?


How to merge two dictionaries in a single expression?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat does the “yield” keyword do?What is the difference between Python's list methods append and extend?How to make a flat list out of list of listsHow do you read from stdin?How do I get the number of elements in a list?How to clone or copy a list?How do I list all files of a directory?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I'm trying to merge all lists in a list of lists that have common elements. I have some working code. However, it seems to break on this example:



def merge_subs(lst_of_lsts):
res = []
for row in lst_of_lsts:
for i, resrow in enumerate(res):
if row[0]==resrow[0]:
res[i] += row[1:]
break
else:
res.append(sorted(row))
return sorted(res)


The input is:



merge_subs([[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]])


My result is:



[[0, 2, 4, 6], [1, 3, 5, 7], [3, 5, 7]]


but I should be getting:



[[0, 2, 4, 6], [1, 3, 5, 7]]









share|improve this question
























  • can you elaborate on the condition of merge? Your code's intention is to check only the first element of each list.

    – adrtam
    Mar 26 at 1:46











  • You result is not the output I get from running that. It does seem like graph connected components.

    – Kenny Ostrom
    Mar 26 at 1:48












  • I don't think your result is what you'll get from the code you've written above..

    – kerwei
    Mar 26 at 2:40

















2















I'm trying to merge all lists in a list of lists that have common elements. I have some working code. However, it seems to break on this example:



def merge_subs(lst_of_lsts):
res = []
for row in lst_of_lsts:
for i, resrow in enumerate(res):
if row[0]==resrow[0]:
res[i] += row[1:]
break
else:
res.append(sorted(row))
return sorted(res)


The input is:



merge_subs([[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]])


My result is:



[[0, 2, 4, 6], [1, 3, 5, 7], [3, 5, 7]]


but I should be getting:



[[0, 2, 4, 6], [1, 3, 5, 7]]









share|improve this question
























  • can you elaborate on the condition of merge? Your code's intention is to check only the first element of each list.

    – adrtam
    Mar 26 at 1:46











  • You result is not the output I get from running that. It does seem like graph connected components.

    – Kenny Ostrom
    Mar 26 at 1:48












  • I don't think your result is what you'll get from the code you've written above..

    – kerwei
    Mar 26 at 2:40













2












2








2








I'm trying to merge all lists in a list of lists that have common elements. I have some working code. However, it seems to break on this example:



def merge_subs(lst_of_lsts):
res = []
for row in lst_of_lsts:
for i, resrow in enumerate(res):
if row[0]==resrow[0]:
res[i] += row[1:]
break
else:
res.append(sorted(row))
return sorted(res)


The input is:



merge_subs([[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]])


My result is:



[[0, 2, 4, 6], [1, 3, 5, 7], [3, 5, 7]]


but I should be getting:



[[0, 2, 4, 6], [1, 3, 5, 7]]









share|improve this question
















I'm trying to merge all lists in a list of lists that have common elements. I have some working code. However, it seems to break on this example:



def merge_subs(lst_of_lsts):
res = []
for row in lst_of_lsts:
for i, resrow in enumerate(res):
if row[0]==resrow[0]:
res[i] += row[1:]
break
else:
res.append(sorted(row))
return sorted(res)


The input is:



merge_subs([[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]])


My result is:



[[0, 2, 4, 6], [1, 3, 5, 7], [3, 5, 7]]


but I should be getting:



[[0, 2, 4, 6], [1, 3, 5, 7]]






python list merge






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 4:00









Pikachu the Parenthesis Wizard

2,1688 gold badges17 silver badges29 bronze badges




2,1688 gold badges17 silver badges29 bronze badges










asked Mar 26 at 1:32









Martin LopezMartin Lopez

498 bronze badges




498 bronze badges












  • can you elaborate on the condition of merge? Your code's intention is to check only the first element of each list.

    – adrtam
    Mar 26 at 1:46











  • You result is not the output I get from running that. It does seem like graph connected components.

    – Kenny Ostrom
    Mar 26 at 1:48












  • I don't think your result is what you'll get from the code you've written above..

    – kerwei
    Mar 26 at 2:40

















  • can you elaborate on the condition of merge? Your code's intention is to check only the first element of each list.

    – adrtam
    Mar 26 at 1:46











  • You result is not the output I get from running that. It does seem like graph connected components.

    – Kenny Ostrom
    Mar 26 at 1:48












  • I don't think your result is what you'll get from the code you've written above..

    – kerwei
    Mar 26 at 2:40
















can you elaborate on the condition of merge? Your code's intention is to check only the first element of each list.

– adrtam
Mar 26 at 1:46





can you elaborate on the condition of merge? Your code's intention is to check only the first element of each list.

– adrtam
Mar 26 at 1:46













You result is not the output I get from running that. It does seem like graph connected components.

– Kenny Ostrom
Mar 26 at 1:48






You result is not the output I get from running that. It does seem like graph connected components.

– Kenny Ostrom
Mar 26 at 1:48














I don't think your result is what you'll get from the code you've written above..

– kerwei
Mar 26 at 2:40





I don't think your result is what you'll get from the code you've written above..

– kerwei
Mar 26 at 2:40












2 Answers
2






active

oldest

votes


















0














You need to use recursion:



def group(d, _start, _c = [], _seen = [], _used=[]):
r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
if not r:
yield set(_c)
for i in d:
if i != _start and i not in _used:
yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
else:
yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)

data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
result = list(map(list, tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i))


Output:



[[0, 2, 4, 6], [1, 3, 5, 7]]





share|improve this answer






























    1














    I agree with @Ajax1234, this problem can be solved using recursion, specifically a tail recursion:



    def merge(lists, results=None):

    if results is None:
    results = []

    if not lists:
    return results

    first = lists[0]
    merged = []
    output = []

    for li in lists[1:]:
    for i in first:
    if i in li:
    merged = merged + li
    break
    else:
    output.append(li)

    merged = merged + first
    results.append(list(set(merged)))

    return merge(output, results)


    And the results look like this:



    >>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
    >>> merge(lists)
    [[1, 3, 5, 7], [0, 2, 4, 6]]





    share|improve this answer























    • Thank you, very readable!

      – Martin Lopez
      Mar 27 at 21:21













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55348640%2fhow-to-merge-lists-with-common-elements-in-a-list-of-lists%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You need to use recursion:



    def group(d, _start, _c = [], _seen = [], _used=[]):
    r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
    if not r:
    yield set(_c)
    for i in d:
    if i != _start and i not in _used:
    yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
    else:
    yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)

    data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
    result = list(map(list, tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i))


    Output:



    [[0, 2, 4, 6], [1, 3, 5, 7]]





    share|improve this answer



























      0














      You need to use recursion:



      def group(d, _start, _c = [], _seen = [], _used=[]):
      r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
      if not r:
      yield set(_c)
      for i in d:
      if i != _start and i not in _used:
      yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
      else:
      yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)

      data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
      result = list(map(list, tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i))


      Output:



      [[0, 2, 4, 6], [1, 3, 5, 7]]





      share|improve this answer

























        0












        0








        0







        You need to use recursion:



        def group(d, _start, _c = [], _seen = [], _used=[]):
        r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
        if not r:
        yield set(_c)
        for i in d:
        if i != _start and i not in _used:
        yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
        else:
        yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)

        data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
        result = list(map(list, tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i))


        Output:



        [[0, 2, 4, 6], [1, 3, 5, 7]]





        share|improve this answer













        You need to use recursion:



        def group(d, _start, _c = [], _seen = [], _used=[]):
        r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
        if not r:
        yield set(_c)
        for i in d:
        if i != _start and i not in _used:
        yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
        else:
        yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)

        data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
        result = list(map(list, tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i))


        Output:



        [[0, 2, 4, 6], [1, 3, 5, 7]]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 1:53









        Ajax1234Ajax1234

        45.7k4 gold badges29 silver badges58 bronze badges




        45.7k4 gold badges29 silver badges58 bronze badges























            1














            I agree with @Ajax1234, this problem can be solved using recursion, specifically a tail recursion:



            def merge(lists, results=None):

            if results is None:
            results = []

            if not lists:
            return results

            first = lists[0]
            merged = []
            output = []

            for li in lists[1:]:
            for i in first:
            if i in li:
            merged = merged + li
            break
            else:
            output.append(li)

            merged = merged + first
            results.append(list(set(merged)))

            return merge(output, results)


            And the results look like this:



            >>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
            >>> merge(lists)
            [[1, 3, 5, 7], [0, 2, 4, 6]]





            share|improve this answer























            • Thank you, very readable!

              – Martin Lopez
              Mar 27 at 21:21















            1














            I agree with @Ajax1234, this problem can be solved using recursion, specifically a tail recursion:



            def merge(lists, results=None):

            if results is None:
            results = []

            if not lists:
            return results

            first = lists[0]
            merged = []
            output = []

            for li in lists[1:]:
            for i in first:
            if i in li:
            merged = merged + li
            break
            else:
            output.append(li)

            merged = merged + first
            results.append(list(set(merged)))

            return merge(output, results)


            And the results look like this:



            >>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
            >>> merge(lists)
            [[1, 3, 5, 7], [0, 2, 4, 6]]





            share|improve this answer























            • Thank you, very readable!

              – Martin Lopez
              Mar 27 at 21:21













            1












            1








            1







            I agree with @Ajax1234, this problem can be solved using recursion, specifically a tail recursion:



            def merge(lists, results=None):

            if results is None:
            results = []

            if not lists:
            return results

            first = lists[0]
            merged = []
            output = []

            for li in lists[1:]:
            for i in first:
            if i in li:
            merged = merged + li
            break
            else:
            output.append(li)

            merged = merged + first
            results.append(list(set(merged)))

            return merge(output, results)


            And the results look like this:



            >>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
            >>> merge(lists)
            [[1, 3, 5, 7], [0, 2, 4, 6]]





            share|improve this answer













            I agree with @Ajax1234, this problem can be solved using recursion, specifically a tail recursion:



            def merge(lists, results=None):

            if results is None:
            results = []

            if not lists:
            return results

            first = lists[0]
            merged = []
            output = []

            for li in lists[1:]:
            for i in first:
            if i in li:
            merged = merged + li
            break
            else:
            output.append(li)

            merged = merged + first
            results.append(list(set(merged)))

            return merge(output, results)


            And the results look like this:



            >>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
            >>> merge(lists)
            [[1, 3, 5, 7], [0, 2, 4, 6]]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 26 at 6:34









            consttconstt

            8041 gold badge10 silver badges12 bronze badges




            8041 gold badge10 silver badges12 bronze badges












            • Thank you, very readable!

              – Martin Lopez
              Mar 27 at 21:21

















            • Thank you, very readable!

              – Martin Lopez
              Mar 27 at 21:21
















            Thank you, very readable!

            – Martin Lopez
            Mar 27 at 21:21





            Thank you, very readable!

            – Martin Lopez
            Mar 27 at 21:21

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55348640%2fhow-to-merge-lists-with-common-elements-in-a-list-of-lists%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현