Merging list with a common element value without sorting it out









up vote
1
down vote

favorite












My problem, is that I have a nested list



l = [
['a','apple',1],
['b', 'banana', 0],
['a', 'artichoke', 'antenna'],
['b', 'brocolli', 'baton'],
['c', None, 22]
]


and i wanted to merge those list that have a common index value also without sorting the resultant list.
My prefered output:



[
['a','apple', 1, 'artichoke', 'antenna'],
['b', 'banana', 0, 'brocolli', 'baton'],
['c', None, 22]
]


I found the solution from here and here
But the output im getting is somehow sorted, which it comes to my current output:



[['c', None, 22], [1, 'antenna', 'apple', 'artichoke', 'a'], [0, 'b', 'banana', 'brocolli', 'baton']]


My code goes:



len_l = len(l)
i = 0
while i < (len_l - 1):
for j in range(i + 1, len_l):

# i,j iterate over all pairs of l's elements including new
# elements from merged pairs. We use len_l because len(l)
# may change as we iterate
i_set = set(l[i])
j_set = set(l[j])
if len(i_set.intersection(j_set)) > 0:
# Remove these two from list
l.pop(j)
l.pop(i)

# Merge them and append to the orig. list
ij_union = list(i_set.union(j_set))
l.append(ij_union)


# len(l) has changed
len_l -= 1

# adjust 'i' because elements shifted
i -= 1

# abort inner loop, continue with next l[i]
break
i += 1
print(l)


I would appreciate the help in here, and im also open to new suggest on how to do this in an easier way, coz honestly the i havent use the union() nor intersection() methods before.
thanx










share|improve this question



























    up vote
    1
    down vote

    favorite












    My problem, is that I have a nested list



    l = [
    ['a','apple',1],
    ['b', 'banana', 0],
    ['a', 'artichoke', 'antenna'],
    ['b', 'brocolli', 'baton'],
    ['c', None, 22]
    ]


    and i wanted to merge those list that have a common index value also without sorting the resultant list.
    My prefered output:



    [
    ['a','apple', 1, 'artichoke', 'antenna'],
    ['b', 'banana', 0, 'brocolli', 'baton'],
    ['c', None, 22]
    ]


    I found the solution from here and here
    But the output im getting is somehow sorted, which it comes to my current output:



    [['c', None, 22], [1, 'antenna', 'apple', 'artichoke', 'a'], [0, 'b', 'banana', 'brocolli', 'baton']]


    My code goes:



    len_l = len(l)
    i = 0
    while i < (len_l - 1):
    for j in range(i + 1, len_l):

    # i,j iterate over all pairs of l's elements including new
    # elements from merged pairs. We use len_l because len(l)
    # may change as we iterate
    i_set = set(l[i])
    j_set = set(l[j])
    if len(i_set.intersection(j_set)) > 0:
    # Remove these two from list
    l.pop(j)
    l.pop(i)

    # Merge them and append to the orig. list
    ij_union = list(i_set.union(j_set))
    l.append(ij_union)


    # len(l) has changed
    len_l -= 1

    # adjust 'i' because elements shifted
    i -= 1

    # abort inner loop, continue with next l[i]
    break
    i += 1
    print(l)


    I would appreciate the help in here, and im also open to new suggest on how to do this in an easier way, coz honestly the i havent use the union() nor intersection() methods before.
    thanx










    share|improve this question

























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      My problem, is that I have a nested list



      l = [
      ['a','apple',1],
      ['b', 'banana', 0],
      ['a', 'artichoke', 'antenna'],
      ['b', 'brocolli', 'baton'],
      ['c', None, 22]
      ]


      and i wanted to merge those list that have a common index value also without sorting the resultant list.
      My prefered output:



      [
      ['a','apple', 1, 'artichoke', 'antenna'],
      ['b', 'banana', 0, 'brocolli', 'baton'],
      ['c', None, 22]
      ]


      I found the solution from here and here
      But the output im getting is somehow sorted, which it comes to my current output:



      [['c', None, 22], [1, 'antenna', 'apple', 'artichoke', 'a'], [0, 'b', 'banana', 'brocolli', 'baton']]


      My code goes:



      len_l = len(l)
      i = 0
      while i < (len_l - 1):
      for j in range(i + 1, len_l):

      # i,j iterate over all pairs of l's elements including new
      # elements from merged pairs. We use len_l because len(l)
      # may change as we iterate
      i_set = set(l[i])
      j_set = set(l[j])
      if len(i_set.intersection(j_set)) > 0:
      # Remove these two from list
      l.pop(j)
      l.pop(i)

      # Merge them and append to the orig. list
      ij_union = list(i_set.union(j_set))
      l.append(ij_union)


      # len(l) has changed
      len_l -= 1

      # adjust 'i' because elements shifted
      i -= 1

      # abort inner loop, continue with next l[i]
      break
      i += 1
      print(l)


      I would appreciate the help in here, and im also open to new suggest on how to do this in an easier way, coz honestly the i havent use the union() nor intersection() methods before.
      thanx










      share|improve this question















      My problem, is that I have a nested list



      l = [
      ['a','apple',1],
      ['b', 'banana', 0],
      ['a', 'artichoke', 'antenna'],
      ['b', 'brocolli', 'baton'],
      ['c', None, 22]
      ]


      and i wanted to merge those list that have a common index value also without sorting the resultant list.
      My prefered output:



      [
      ['a','apple', 1, 'artichoke', 'antenna'],
      ['b', 'banana', 0, 'brocolli', 'baton'],
      ['c', None, 22]
      ]


      I found the solution from here and here
      But the output im getting is somehow sorted, which it comes to my current output:



      [['c', None, 22], [1, 'antenna', 'apple', 'artichoke', 'a'], [0, 'b', 'banana', 'brocolli', 'baton']]


      My code goes:



      len_l = len(l)
      i = 0
      while i < (len_l - 1):
      for j in range(i + 1, len_l):

      # i,j iterate over all pairs of l's elements including new
      # elements from merged pairs. We use len_l because len(l)
      # may change as we iterate
      i_set = set(l[i])
      j_set = set(l[j])
      if len(i_set.intersection(j_set)) > 0:
      # Remove these two from list
      l.pop(j)
      l.pop(i)

      # Merge them and append to the orig. list
      ij_union = list(i_set.union(j_set))
      l.append(ij_union)


      # len(l) has changed
      len_l -= 1

      # adjust 'i' because elements shifted
      i -= 1

      # abort inner loop, continue with next l[i]
      break
      i += 1
      print(l)


      I would appreciate the help in here, and im also open to new suggest on how to do this in an easier way, coz honestly the i havent use the union() nor intersection() methods before.
      thanx







      python python-3.x list






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 10 at 15:14









      Jon Clements

      97k19168213




      97k19168213










      asked Nov 10 at 14:59









      rockStar

      1,156820




      1,156820






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          You can use a dictionary with the first element of each list as the key and extend a list each time as they're encountered in the list-of-lists, eg:



          data = [
          ['a','apple',1],
          ['b', 'banana', 0],
          ['a', 'artichoke', 'antenna'],
          ['b', 'brocolli', 'baton'],
          ['c', None, 22]
          ]


          Then we:



          d = 
          for k, *vals in data:
          d.setdefault(k, ).extend(vals)


          Optionally you can use d = collections.OrderedDict() here if it's completely necessary to guarantee the order of the keys is as seen in the list.



          Which gives you a d of:



          'a': ['apple', 1, 'artichoke', 'antenna'],
          'b': ['banana', 0, 'brocolli', 'baton'],
          'c': [None, 22]


          If you then want to unpack back to a lists of lists (although it's probably more useful being a dict) then you can do:



          new_data = [[k, *v] for k, v in d.items()]


          To get:



          [['a', 'apple', 1, 'artichoke', 'antenna'],
          ['b', 'banana', 0, 'brocolli', 'baton'],
          ['c', None, 22]]





          share|improve this answer




















          • thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
            – rockStar
            Nov 10 at 15:22






          • 1




            @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
            – Jon Clements
            Nov 10 at 15:29










          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',
          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%2f53240185%2fmerging-list-with-a-common-element-value-without-sorting-it-out%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          4
          down vote



          accepted










          You can use a dictionary with the first element of each list as the key and extend a list each time as they're encountered in the list-of-lists, eg:



          data = [
          ['a','apple',1],
          ['b', 'banana', 0],
          ['a', 'artichoke', 'antenna'],
          ['b', 'brocolli', 'baton'],
          ['c', None, 22]
          ]


          Then we:



          d = 
          for k, *vals in data:
          d.setdefault(k, ).extend(vals)


          Optionally you can use d = collections.OrderedDict() here if it's completely necessary to guarantee the order of the keys is as seen in the list.



          Which gives you a d of:



          'a': ['apple', 1, 'artichoke', 'antenna'],
          'b': ['banana', 0, 'brocolli', 'baton'],
          'c': [None, 22]


          If you then want to unpack back to a lists of lists (although it's probably more useful being a dict) then you can do:



          new_data = [[k, *v] for k, v in d.items()]


          To get:



          [['a', 'apple', 1, 'artichoke', 'antenna'],
          ['b', 'banana', 0, 'brocolli', 'baton'],
          ['c', None, 22]]





          share|improve this answer




















          • thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
            – rockStar
            Nov 10 at 15:22






          • 1




            @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
            – Jon Clements
            Nov 10 at 15:29














          up vote
          4
          down vote



          accepted










          You can use a dictionary with the first element of each list as the key and extend a list each time as they're encountered in the list-of-lists, eg:



          data = [
          ['a','apple',1],
          ['b', 'banana', 0],
          ['a', 'artichoke', 'antenna'],
          ['b', 'brocolli', 'baton'],
          ['c', None, 22]
          ]


          Then we:



          d = 
          for k, *vals in data:
          d.setdefault(k, ).extend(vals)


          Optionally you can use d = collections.OrderedDict() here if it's completely necessary to guarantee the order of the keys is as seen in the list.



          Which gives you a d of:



          'a': ['apple', 1, 'artichoke', 'antenna'],
          'b': ['banana', 0, 'brocolli', 'baton'],
          'c': [None, 22]


          If you then want to unpack back to a lists of lists (although it's probably more useful being a dict) then you can do:



          new_data = [[k, *v] for k, v in d.items()]


          To get:



          [['a', 'apple', 1, 'artichoke', 'antenna'],
          ['b', 'banana', 0, 'brocolli', 'baton'],
          ['c', None, 22]]





          share|improve this answer




















          • thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
            – rockStar
            Nov 10 at 15:22






          • 1




            @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
            – Jon Clements
            Nov 10 at 15:29












          up vote
          4
          down vote



          accepted







          up vote
          4
          down vote



          accepted






          You can use a dictionary with the first element of each list as the key and extend a list each time as they're encountered in the list-of-lists, eg:



          data = [
          ['a','apple',1],
          ['b', 'banana', 0],
          ['a', 'artichoke', 'antenna'],
          ['b', 'brocolli', 'baton'],
          ['c', None, 22]
          ]


          Then we:



          d = 
          for k, *vals in data:
          d.setdefault(k, ).extend(vals)


          Optionally you can use d = collections.OrderedDict() here if it's completely necessary to guarantee the order of the keys is as seen in the list.



          Which gives you a d of:



          'a': ['apple', 1, 'artichoke', 'antenna'],
          'b': ['banana', 0, 'brocolli', 'baton'],
          'c': [None, 22]


          If you then want to unpack back to a lists of lists (although it's probably more useful being a dict) then you can do:



          new_data = [[k, *v] for k, v in d.items()]


          To get:



          [['a', 'apple', 1, 'artichoke', 'antenna'],
          ['b', 'banana', 0, 'brocolli', 'baton'],
          ['c', None, 22]]





          share|improve this answer












          You can use a dictionary with the first element of each list as the key and extend a list each time as they're encountered in the list-of-lists, eg:



          data = [
          ['a','apple',1],
          ['b', 'banana', 0],
          ['a', 'artichoke', 'antenna'],
          ['b', 'brocolli', 'baton'],
          ['c', None, 22]
          ]


          Then we:



          d = 
          for k, *vals in data:
          d.setdefault(k, ).extend(vals)


          Optionally you can use d = collections.OrderedDict() here if it's completely necessary to guarantee the order of the keys is as seen in the list.



          Which gives you a d of:



          'a': ['apple', 1, 'artichoke', 'antenna'],
          'b': ['banana', 0, 'brocolli', 'baton'],
          'c': [None, 22]


          If you then want to unpack back to a lists of lists (although it's probably more useful being a dict) then you can do:



          new_data = [[k, *v] for k, v in d.items()]


          To get:



          [['a', 'apple', 1, 'artichoke', 'antenna'],
          ['b', 'banana', 0, 'brocolli', 'baton'],
          ['c', None, 22]]






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 15:07









          Jon Clements

          97k19168213




          97k19168213











          • thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
            – rockStar
            Nov 10 at 15:22






          • 1




            @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
            – Jon Clements
            Nov 10 at 15:29
















          • thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
            – rockStar
            Nov 10 at 15:22






          • 1




            @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
            – Jon Clements
            Nov 10 at 15:29















          thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
          – rockStar
          Nov 10 at 15:22




          thanx for the response, and i learned a new thing here coz i didnt know that you can actually do for k, *vals in data: where the first element of the list is k and the remaining values would be in vals.
          – rockStar
          Nov 10 at 15:22




          1




          1




          @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
          – Jon Clements
          Nov 10 at 15:29




          @rockStar it's fairly useful sometimes - you might want to check out: python.org/dev/peps/pep-3132
          – Jon Clements
          Nov 10 at 15:29

















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240185%2fmerging-list-with-a-common-element-value-without-sorting-it-out%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







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

          Museum of Modern and Contemporary Art of Trento and Rovereto