Python tuples manipulation











up vote
2
down vote

favorite












I have a tuple in Python like this -



a = ((-,-,x), (-,-,x), (-,-,y), (-,-,z), (-,-,z), (-,-,z))


Now, I want to group the tuples with the same third element. I have to convert this tuple,a into



b = (((-,-,x), (-,-,x)), ((-,-,y)), ((-,-,z), (-,-,z), (-,-,z)))


How do I write Python code for this? To convert a into b? Since tuples are immutable I'm not able to write the code successfully.










share|improve this question






















  • - is string or?
    – Dejan Marić
    Nov 8 at 10:17






  • 1




    I don't get why tuples immutability is a problem. You here construct a new tuple.
    – Willem Van Onsem
    Nov 8 at 10:20






  • 1




    I had to add so many ' :( - next time please post data structures that we can copy-paste into the Python interpreter.
    – timgeb
    Nov 8 at 10:23










  • @DejanMarić '-' can be any datatype. I just wanted the logic irrespective of datatype.
    – Keerthan Bhat
    Nov 8 at 10:24






  • 1




    @timgeb Alright noted, my bad. Thanks.
    – Keerthan Bhat
    Nov 8 at 10:26















up vote
2
down vote

favorite












I have a tuple in Python like this -



a = ((-,-,x), (-,-,x), (-,-,y), (-,-,z), (-,-,z), (-,-,z))


Now, I want to group the tuples with the same third element. I have to convert this tuple,a into



b = (((-,-,x), (-,-,x)), ((-,-,y)), ((-,-,z), (-,-,z), (-,-,z)))


How do I write Python code for this? To convert a into b? Since tuples are immutable I'm not able to write the code successfully.










share|improve this question






















  • - is string or?
    – Dejan Marić
    Nov 8 at 10:17






  • 1




    I don't get why tuples immutability is a problem. You here construct a new tuple.
    – Willem Van Onsem
    Nov 8 at 10:20






  • 1




    I had to add so many ' :( - next time please post data structures that we can copy-paste into the Python interpreter.
    – timgeb
    Nov 8 at 10:23










  • @DejanMarić '-' can be any datatype. I just wanted the logic irrespective of datatype.
    – Keerthan Bhat
    Nov 8 at 10:24






  • 1




    @timgeb Alright noted, my bad. Thanks.
    – Keerthan Bhat
    Nov 8 at 10:26













up vote
2
down vote

favorite









up vote
2
down vote

favorite











I have a tuple in Python like this -



a = ((-,-,x), (-,-,x), (-,-,y), (-,-,z), (-,-,z), (-,-,z))


Now, I want to group the tuples with the same third element. I have to convert this tuple,a into



b = (((-,-,x), (-,-,x)), ((-,-,y)), ((-,-,z), (-,-,z), (-,-,z)))


How do I write Python code for this? To convert a into b? Since tuples are immutable I'm not able to write the code successfully.










share|improve this question













I have a tuple in Python like this -



a = ((-,-,x), (-,-,x), (-,-,y), (-,-,z), (-,-,z), (-,-,z))


Now, I want to group the tuples with the same third element. I have to convert this tuple,a into



b = (((-,-,x), (-,-,x)), ((-,-,y)), ((-,-,z), (-,-,z), (-,-,z)))


How do I write Python code for this? To convert a into b? Since tuples are immutable I'm not able to write the code successfully.







python django tuples






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 8 at 10:13









Keerthan Bhat

879




879












  • - is string or?
    – Dejan Marić
    Nov 8 at 10:17






  • 1




    I don't get why tuples immutability is a problem. You here construct a new tuple.
    – Willem Van Onsem
    Nov 8 at 10:20






  • 1




    I had to add so many ' :( - next time please post data structures that we can copy-paste into the Python interpreter.
    – timgeb
    Nov 8 at 10:23










  • @DejanMarić '-' can be any datatype. I just wanted the logic irrespective of datatype.
    – Keerthan Bhat
    Nov 8 at 10:24






  • 1




    @timgeb Alright noted, my bad. Thanks.
    – Keerthan Bhat
    Nov 8 at 10:26


















  • - is string or?
    – Dejan Marić
    Nov 8 at 10:17






  • 1




    I don't get why tuples immutability is a problem. You here construct a new tuple.
    – Willem Van Onsem
    Nov 8 at 10:20






  • 1




    I had to add so many ' :( - next time please post data structures that we can copy-paste into the Python interpreter.
    – timgeb
    Nov 8 at 10:23










  • @DejanMarić '-' can be any datatype. I just wanted the logic irrespective of datatype.
    – Keerthan Bhat
    Nov 8 at 10:24






  • 1




    @timgeb Alright noted, my bad. Thanks.
    – Keerthan Bhat
    Nov 8 at 10:26
















- is string or?
– Dejan Marić
Nov 8 at 10:17




- is string or?
– Dejan Marić
Nov 8 at 10:17




1




1




I don't get why tuples immutability is a problem. You here construct a new tuple.
– Willem Van Onsem
Nov 8 at 10:20




I don't get why tuples immutability is a problem. You here construct a new tuple.
– Willem Van Onsem
Nov 8 at 10:20




1




1




I had to add so many ' :( - next time please post data structures that we can copy-paste into the Python interpreter.
– timgeb
Nov 8 at 10:23




I had to add so many ' :( - next time please post data structures that we can copy-paste into the Python interpreter.
– timgeb
Nov 8 at 10:23












@DejanMarić '-' can be any datatype. I just wanted the logic irrespective of datatype.
– Keerthan Bhat
Nov 8 at 10:24




@DejanMarić '-' can be any datatype. I just wanted the logic irrespective of datatype.
– Keerthan Bhat
Nov 8 at 10:24




1




1




@timgeb Alright noted, my bad. Thanks.
– Keerthan Bhat
Nov 8 at 10:26




@timgeb Alright noted, my bad. Thanks.
– Keerthan Bhat
Nov 8 at 10:26












3 Answers
3






active

oldest

votes

















up vote
3
down vote



accepted










This can be done with itertools.groupby.



>>> from operator import itemgetter
>>> from itertools import groupby
>>>
>>> a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))
>>> tuple(tuple(grp) for _, grp in groupby(a, key=itemgetter(-1)))
>>>
((('-', '-', 'x'), ('-', '-', 'x')),
(('-', '-', 'y'),),
(('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))


It's assumed that groups of equal last elements cannot be interrupted (like in your sample data). If they can, you need to sort a with key=itemgetter(-1) first.




...can you explain "interrupted"?




Sure. What I mean is that groupby lumps together groups of consecutive elements where key returns the same value. So if we had something like



b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))


then the groupby from above would create three groups, not two.



>>> b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))
>>> tuple(tuple(grp) for _, grp in groupby(b, key=itemgetter(-1)))
>>> ((('-', '-', 'z'),), (('-', '-', 'x'),), (('-', '-', 'z'),))


If you don't want that to happen, sort b first.



>>> last = itemgetter(-1)
>>> tuple(tuple(grp) for _, grp in groupby(sorted(b, key=last), key=last))
>>> ((('-', '-', 'x'),), (('-', '-', 'z'), ('-', '-', 'z')))





share|improve this answer























  • ...can you explain "interrupted"?
    – mikuszefski
    Nov 8 at 10:24










  • Yep, OK. Thanks.
    – mikuszefski
    Nov 8 at 10:29


















up vote
0
down vote













Use itertools.groupby:



from itertools import groupby

a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))

print(tuple(tuple(x) for _, x in groupby(a)))
# ((('-', '-', 'x'), ('-', '-', 'x')), (('-', '-', 'y'),), (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))





share|improve this answer




























    up vote
    0
    down vote













    Given the elements are already ordered by the last element (well the tuples with x as last element, etc. are positioned in a sequence), we can use itertools.groupby:



    from itertools import groupby
    from operator import itemgetter

    b = tuple(tuple(vs) for _, vs in groupby(a, itemgetter(-1)))





    share|improve this answer





















      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%2f53205572%2fpython-tuples-manipulation%23new-answer', 'question_page');
      }
      );

      Post as a guest
































      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      3
      down vote



      accepted










      This can be done with itertools.groupby.



      >>> from operator import itemgetter
      >>> from itertools import groupby
      >>>
      >>> a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(a, key=itemgetter(-1)))
      >>>
      ((('-', '-', 'x'), ('-', '-', 'x')),
      (('-', '-', 'y'),),
      (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))


      It's assumed that groups of equal last elements cannot be interrupted (like in your sample data). If they can, you need to sort a with key=itemgetter(-1) first.




      ...can you explain "interrupted"?




      Sure. What I mean is that groupby lumps together groups of consecutive elements where key returns the same value. So if we had something like



      b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))


      then the groupby from above would create three groups, not two.



      >>> b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(b, key=itemgetter(-1)))
      >>> ((('-', '-', 'z'),), (('-', '-', 'x'),), (('-', '-', 'z'),))


      If you don't want that to happen, sort b first.



      >>> last = itemgetter(-1)
      >>> tuple(tuple(grp) for _, grp in groupby(sorted(b, key=last), key=last))
      >>> ((('-', '-', 'x'),), (('-', '-', 'z'), ('-', '-', 'z')))





      share|improve this answer























      • ...can you explain "interrupted"?
        – mikuszefski
        Nov 8 at 10:24










      • Yep, OK. Thanks.
        – mikuszefski
        Nov 8 at 10:29















      up vote
      3
      down vote



      accepted










      This can be done with itertools.groupby.



      >>> from operator import itemgetter
      >>> from itertools import groupby
      >>>
      >>> a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(a, key=itemgetter(-1)))
      >>>
      ((('-', '-', 'x'), ('-', '-', 'x')),
      (('-', '-', 'y'),),
      (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))


      It's assumed that groups of equal last elements cannot be interrupted (like in your sample data). If they can, you need to sort a with key=itemgetter(-1) first.




      ...can you explain "interrupted"?




      Sure. What I mean is that groupby lumps together groups of consecutive elements where key returns the same value. So if we had something like



      b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))


      then the groupby from above would create three groups, not two.



      >>> b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(b, key=itemgetter(-1)))
      >>> ((('-', '-', 'z'),), (('-', '-', 'x'),), (('-', '-', 'z'),))


      If you don't want that to happen, sort b first.



      >>> last = itemgetter(-1)
      >>> tuple(tuple(grp) for _, grp in groupby(sorted(b, key=last), key=last))
      >>> ((('-', '-', 'x'),), (('-', '-', 'z'), ('-', '-', 'z')))





      share|improve this answer























      • ...can you explain "interrupted"?
        – mikuszefski
        Nov 8 at 10:24










      • Yep, OK. Thanks.
        – mikuszefski
        Nov 8 at 10:29













      up vote
      3
      down vote



      accepted







      up vote
      3
      down vote



      accepted






      This can be done with itertools.groupby.



      >>> from operator import itemgetter
      >>> from itertools import groupby
      >>>
      >>> a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(a, key=itemgetter(-1)))
      >>>
      ((('-', '-', 'x'), ('-', '-', 'x')),
      (('-', '-', 'y'),),
      (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))


      It's assumed that groups of equal last elements cannot be interrupted (like in your sample data). If they can, you need to sort a with key=itemgetter(-1) first.




      ...can you explain "interrupted"?




      Sure. What I mean is that groupby lumps together groups of consecutive elements where key returns the same value. So if we had something like



      b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))


      then the groupby from above would create three groups, not two.



      >>> b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(b, key=itemgetter(-1)))
      >>> ((('-', '-', 'z'),), (('-', '-', 'x'),), (('-', '-', 'z'),))


      If you don't want that to happen, sort b first.



      >>> last = itemgetter(-1)
      >>> tuple(tuple(grp) for _, grp in groupby(sorted(b, key=last), key=last))
      >>> ((('-', '-', 'x'),), (('-', '-', 'z'), ('-', '-', 'z')))





      share|improve this answer














      This can be done with itertools.groupby.



      >>> from operator import itemgetter
      >>> from itertools import groupby
      >>>
      >>> a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(a, key=itemgetter(-1)))
      >>>
      ((('-', '-', 'x'), ('-', '-', 'x')),
      (('-', '-', 'y'),),
      (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))


      It's assumed that groups of equal last elements cannot be interrupted (like in your sample data). If they can, you need to sort a with key=itemgetter(-1) first.




      ...can you explain "interrupted"?




      Sure. What I mean is that groupby lumps together groups of consecutive elements where key returns the same value. So if we had something like



      b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))


      then the groupby from above would create three groups, not two.



      >>> b = (('-','-','z'), ('-', '-', 'x'), ('-','-','z'))
      >>> tuple(tuple(grp) for _, grp in groupby(b, key=itemgetter(-1)))
      >>> ((('-', '-', 'z'),), (('-', '-', 'x'),), (('-', '-', 'z'),))


      If you don't want that to happen, sort b first.



      >>> last = itemgetter(-1)
      >>> tuple(tuple(grp) for _, grp in groupby(sorted(b, key=last), key=last))
      >>> ((('-', '-', 'x'),), (('-', '-', 'z'), ('-', '-', 'z')))






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 8 at 10:29

























      answered Nov 8 at 10:20









      timgeb

      43.3k106085




      43.3k106085












      • ...can you explain "interrupted"?
        – mikuszefski
        Nov 8 at 10:24










      • Yep, OK. Thanks.
        – mikuszefski
        Nov 8 at 10:29


















      • ...can you explain "interrupted"?
        – mikuszefski
        Nov 8 at 10:24










      • Yep, OK. Thanks.
        – mikuszefski
        Nov 8 at 10:29
















      ...can you explain "interrupted"?
      – mikuszefski
      Nov 8 at 10:24




      ...can you explain "interrupted"?
      – mikuszefski
      Nov 8 at 10:24












      Yep, OK. Thanks.
      – mikuszefski
      Nov 8 at 10:29




      Yep, OK. Thanks.
      – mikuszefski
      Nov 8 at 10:29












      up vote
      0
      down vote













      Use itertools.groupby:



      from itertools import groupby

      a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))

      print(tuple(tuple(x) for _, x in groupby(a)))
      # ((('-', '-', 'x'), ('-', '-', 'x')), (('-', '-', 'y'),), (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))





      share|improve this answer

























        up vote
        0
        down vote













        Use itertools.groupby:



        from itertools import groupby

        a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))

        print(tuple(tuple(x) for _, x in groupby(a)))
        # ((('-', '-', 'x'), ('-', '-', 'x')), (('-', '-', 'y'),), (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))





        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          Use itertools.groupby:



          from itertools import groupby

          a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))

          print(tuple(tuple(x) for _, x in groupby(a)))
          # ((('-', '-', 'x'), ('-', '-', 'x')), (('-', '-', 'y'),), (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))





          share|improve this answer












          Use itertools.groupby:



          from itertools import groupby

          a = (('-','-','x'), ('-','-','x'), ('-','-','y'), ('-','-','z'), ('-','-','z'), ('-','-','z'))

          print(tuple(tuple(x) for _, x in groupby(a)))
          # ((('-', '-', 'x'), ('-', '-', 'x')), (('-', '-', 'y'),), (('-', '-', 'z'), ('-', '-', 'z'), ('-', '-', 'z')))






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 at 10:20









          Austin

          7,8843827




          7,8843827






















              up vote
              0
              down vote













              Given the elements are already ordered by the last element (well the tuples with x as last element, etc. are positioned in a sequence), we can use itertools.groupby:



              from itertools import groupby
              from operator import itemgetter

              b = tuple(tuple(vs) for _, vs in groupby(a, itemgetter(-1)))





              share|improve this answer

























                up vote
                0
                down vote













                Given the elements are already ordered by the last element (well the tuples with x as last element, etc. are positioned in a sequence), we can use itertools.groupby:



                from itertools import groupby
                from operator import itemgetter

                b = tuple(tuple(vs) for _, vs in groupby(a, itemgetter(-1)))





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Given the elements are already ordered by the last element (well the tuples with x as last element, etc. are positioned in a sequence), we can use itertools.groupby:



                  from itertools import groupby
                  from operator import itemgetter

                  b = tuple(tuple(vs) for _, vs in groupby(a, itemgetter(-1)))





                  share|improve this answer












                  Given the elements are already ordered by the last element (well the tuples with x as last element, etc. are positioned in a sequence), we can use itertools.groupby:



                  from itertools import groupby
                  from operator import itemgetter

                  b = tuple(tuple(vs) for _, vs in groupby(a, itemgetter(-1)))






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 8 at 10:20









                  Willem Van Onsem

                  139k16131221




                  139k16131221






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205572%2fpython-tuples-manipulation%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest




















































































                      Popular posts from this blog

                      Landwehr

                      Reims

                      Schenkenzell