Pythonic Way to Sort a List of Comma Separated Numbers











up vote
3
down vote

favorite












Sample Input



20, 71146620
100, 26867616
10, 02513583
10, 52811698
100, 23859051


I read it in from a file as a command line argument to a list with



lin = [i.strip() for i in open(sys.argv[1]).readlines()]


that list looks like ['20, 71146620', '100, 26867616', '10, 02513583', '10, 52811698', '100, 23859051']



My hope is to find the most pythonic way to sort this list, first for the first value and then for the second so that it looks like:



['10, 02513583', '10, 52811698', '20, 71146620', '100, 23859051', '100, 26867616', ]



I'm currently trying to convert it to a list of key value pairs, but I'm not sure that's the right direction to take.










share|improve this question






















  • Two things to remember - 1/ Standard Dictionaries only have 1 value per key so you would loose on 10: entry, 2/ Standard Dictionaries can not be "sorted". So key, value pairs is the wrong name if your example data & output is correct.
    – Steve Barnes
    Oct 14 '13 at 5:17















up vote
3
down vote

favorite












Sample Input



20, 71146620
100, 26867616
10, 02513583
10, 52811698
100, 23859051


I read it in from a file as a command line argument to a list with



lin = [i.strip() for i in open(sys.argv[1]).readlines()]


that list looks like ['20, 71146620', '100, 26867616', '10, 02513583', '10, 52811698', '100, 23859051']



My hope is to find the most pythonic way to sort this list, first for the first value and then for the second so that it looks like:



['10, 02513583', '10, 52811698', '20, 71146620', '100, 23859051', '100, 26867616', ]



I'm currently trying to convert it to a list of key value pairs, but I'm not sure that's the right direction to take.










share|improve this question






















  • Two things to remember - 1/ Standard Dictionaries only have 1 value per key so you would loose on 10: entry, 2/ Standard Dictionaries can not be "sorted". So key, value pairs is the wrong name if your example data & output is correct.
    – Steve Barnes
    Oct 14 '13 at 5:17













up vote
3
down vote

favorite









up vote
3
down vote

favorite











Sample Input



20, 71146620
100, 26867616
10, 02513583
10, 52811698
100, 23859051


I read it in from a file as a command line argument to a list with



lin = [i.strip() for i in open(sys.argv[1]).readlines()]


that list looks like ['20, 71146620', '100, 26867616', '10, 02513583', '10, 52811698', '100, 23859051']



My hope is to find the most pythonic way to sort this list, first for the first value and then for the second so that it looks like:



['10, 02513583', '10, 52811698', '20, 71146620', '100, 23859051', '100, 26867616', ]



I'm currently trying to convert it to a list of key value pairs, but I'm not sure that's the right direction to take.










share|improve this question













Sample Input



20, 71146620
100, 26867616
10, 02513583
10, 52811698
100, 23859051


I read it in from a file as a command line argument to a list with



lin = [i.strip() for i in open(sys.argv[1]).readlines()]


that list looks like ['20, 71146620', '100, 26867616', '10, 02513583', '10, 52811698', '100, 23859051']



My hope is to find the most pythonic way to sort this list, first for the first value and then for the second so that it looks like:



['10, 02513583', '10, 52811698', '20, 71146620', '100, 23859051', '100, 26867616', ]



I'm currently trying to convert it to a list of key value pairs, but I'm not sure that's the right direction to take.







python list sorting






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Oct 14 '13 at 4:41









frankV

1,67442439




1,67442439












  • Two things to remember - 1/ Standard Dictionaries only have 1 value per key so you would loose on 10: entry, 2/ Standard Dictionaries can not be "sorted". So key, value pairs is the wrong name if your example data & output is correct.
    – Steve Barnes
    Oct 14 '13 at 5:17


















  • Two things to remember - 1/ Standard Dictionaries only have 1 value per key so you would loose on 10: entry, 2/ Standard Dictionaries can not be "sorted". So key, value pairs is the wrong name if your example data & output is correct.
    – Steve Barnes
    Oct 14 '13 at 5:17
















Two things to remember - 1/ Standard Dictionaries only have 1 value per key so you would loose on 10: entry, 2/ Standard Dictionaries can not be "sorted". So key, value pairs is the wrong name if your example data & output is correct.
– Steve Barnes
Oct 14 '13 at 5:17




Two things to remember - 1/ Standard Dictionaries only have 1 value per key so you would loose on 10: entry, 2/ Standard Dictionaries can not be "sorted". So key, value pairs is the wrong name if your example data & output is correct.
– Steve Barnes
Oct 14 '13 at 5:17












4 Answers
4






active

oldest

votes

















up vote
4
down vote



accepted










The easiest thing to do is to parse the pairs into lists and then just sort them:



lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
lin = sorted(lin)


In case you want to sort numerically, just cast to numbers:



lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
lin = sorted(lin)





share|improve this answer























  • Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
    – frankV
    Oct 14 '13 at 4:47


















up vote
1
down vote













import sys
with open(sys.argv[1]) as f:
lin = sorted([[int(j) for j in i.split(",")] for i in f])
print lin





share|improve this answer






























    up vote
    1
    down vote













    You can sort the lines as strings, by using a key function



    def two_ints(s):
    return map(int, s.split(","))

    with open("num.txt") as f:
    for line in sorted(f, key=two_ints):
    print line


    It really depends whether you want the result to be a list of strings, or a list of lists of ints.



    Once you have converted to int, there is no way to recover the leading zero on "02513583", so leaving the result as strings may be preferable






    share|improve this answer




























      up vote
      0
      down vote













      why not just use the csv module and feed it to sort (with a string to integer conversion)



      import csv

      with open("test.csv") as f:
      cr = csv.reader(f)
      result = sorted(list(map(int,row)) for row in cr)


      outcome:



      >>> result
      [[10, 2513583],
      [10, 52811698],
      [20, 71146620],
      [100, 23859051],
      [100, 26867616]]


      sort does exactly what's asked here: it uses natural sorting order of lists






      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%2f19353638%2fpythonic-way-to-sort-a-list-of-comma-separated-numbers%23new-answer', 'question_page');
        }
        );

        Post as a guest
































        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        4
        down vote



        accepted










        The easiest thing to do is to parse the pairs into lists and then just sort them:



        lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)


        In case you want to sort numerically, just cast to numbers:



        lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)





        share|improve this answer























        • Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
          – frankV
          Oct 14 '13 at 4:47















        up vote
        4
        down vote



        accepted










        The easiest thing to do is to parse the pairs into lists and then just sort them:



        lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)


        In case you want to sort numerically, just cast to numbers:



        lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)





        share|improve this answer























        • Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
          – frankV
          Oct 14 '13 at 4:47













        up vote
        4
        down vote



        accepted







        up vote
        4
        down vote



        accepted






        The easiest thing to do is to parse the pairs into lists and then just sort them:



        lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)


        In case you want to sort numerically, just cast to numbers:



        lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)





        share|improve this answer














        The easiest thing to do is to parse the pairs into lists and then just sort them:



        lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)


        In case you want to sort numerically, just cast to numbers:



        lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
        lin = sorted(lin)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Oct 14 '13 at 4:49

























        answered Oct 14 '13 at 4:44









        Petar Ivanov

        67.1k66280




        67.1k66280












        • Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
          – frankV
          Oct 14 '13 at 4:47


















        • Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
          – frankV
          Oct 14 '13 at 4:47
















        Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
        – frankV
        Oct 14 '13 at 4:47




        Yes I was hoping for numerical sort. Thank you both. Wish I could select both as correct.
        – frankV
        Oct 14 '13 at 4:47












        up vote
        1
        down vote













        import sys
        with open(sys.argv[1]) as f:
        lin = sorted([[int(j) for j in i.split(",")] for i in f])
        print lin





        share|improve this answer



























          up vote
          1
          down vote













          import sys
          with open(sys.argv[1]) as f:
          lin = sorted([[int(j) for j in i.split(",")] for i in f])
          print lin





          share|improve this answer

























            up vote
            1
            down vote










            up vote
            1
            down vote









            import sys
            with open(sys.argv[1]) as f:
            lin = sorted([[int(j) for j in i.split(",")] for i in f])
            print lin





            share|improve this answer














            import sys
            with open(sys.argv[1]) as f:
            lin = sorted([[int(j) for j in i.split(",")] for i in f])
            print lin






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 14 '13 at 4:50

























            answered Oct 14 '13 at 4:45









            Robᵩ

            113k12129212




            113k12129212






















                up vote
                1
                down vote













                You can sort the lines as strings, by using a key function



                def two_ints(s):
                return map(int, s.split(","))

                with open("num.txt") as f:
                for line in sorted(f, key=two_ints):
                print line


                It really depends whether you want the result to be a list of strings, or a list of lists of ints.



                Once you have converted to int, there is no way to recover the leading zero on "02513583", so leaving the result as strings may be preferable






                share|improve this answer

























                  up vote
                  1
                  down vote













                  You can sort the lines as strings, by using a key function



                  def two_ints(s):
                  return map(int, s.split(","))

                  with open("num.txt") as f:
                  for line in sorted(f, key=two_ints):
                  print line


                  It really depends whether you want the result to be a list of strings, or a list of lists of ints.



                  Once you have converted to int, there is no way to recover the leading zero on "02513583", so leaving the result as strings may be preferable






                  share|improve this answer























                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    You can sort the lines as strings, by using a key function



                    def two_ints(s):
                    return map(int, s.split(","))

                    with open("num.txt") as f:
                    for line in sorted(f, key=two_ints):
                    print line


                    It really depends whether you want the result to be a list of strings, or a list of lists of ints.



                    Once you have converted to int, there is no way to recover the leading zero on "02513583", so leaving the result as strings may be preferable






                    share|improve this answer












                    You can sort the lines as strings, by using a key function



                    def two_ints(s):
                    return map(int, s.split(","))

                    with open("num.txt") as f:
                    for line in sorted(f, key=two_ints):
                    print line


                    It really depends whether you want the result to be a list of strings, or a list of lists of ints.



                    Once you have converted to int, there is no way to recover the leading zero on "02513583", so leaving the result as strings may be preferable







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 14 '13 at 5:09









                    John La Rooy

                    205k37270424




                    205k37270424






















                        up vote
                        0
                        down vote













                        why not just use the csv module and feed it to sort (with a string to integer conversion)



                        import csv

                        with open("test.csv") as f:
                        cr = csv.reader(f)
                        result = sorted(list(map(int,row)) for row in cr)


                        outcome:



                        >>> result
                        [[10, 2513583],
                        [10, 52811698],
                        [20, 71146620],
                        [100, 23859051],
                        [100, 26867616]]


                        sort does exactly what's asked here: it uses natural sorting order of lists






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          why not just use the csv module and feed it to sort (with a string to integer conversion)



                          import csv

                          with open("test.csv") as f:
                          cr = csv.reader(f)
                          result = sorted(list(map(int,row)) for row in cr)


                          outcome:



                          >>> result
                          [[10, 2513583],
                          [10, 52811698],
                          [20, 71146620],
                          [100, 23859051],
                          [100, 26867616]]


                          sort does exactly what's asked here: it uses natural sorting order of lists






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            why not just use the csv module and feed it to sort (with a string to integer conversion)



                            import csv

                            with open("test.csv") as f:
                            cr = csv.reader(f)
                            result = sorted(list(map(int,row)) for row in cr)


                            outcome:



                            >>> result
                            [[10, 2513583],
                            [10, 52811698],
                            [20, 71146620],
                            [100, 23859051],
                            [100, 26867616]]


                            sort does exactly what's asked here: it uses natural sorting order of lists






                            share|improve this answer












                            why not just use the csv module and feed it to sort (with a string to integer conversion)



                            import csv

                            with open("test.csv") as f:
                            cr = csv.reader(f)
                            result = sorted(list(map(int,row)) for row in cr)


                            outcome:



                            >>> result
                            [[10, 2513583],
                            [10, 52811698],
                            [20, 71146620],
                            [100, 23859051],
                            [100, 26867616]]


                            sort does exactly what's asked here: it uses natural sorting order of lists







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 22 hours ago









                            Jean-François Fabre

                            96.6k949106




                            96.6k949106






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19353638%2fpythonic-way-to-sort-a-list-of-comma-separated-numbers%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest




















































































                                Popular posts from this blog

                                Xamarin.iOS Cant Deploy on Iphone

                                Glorious Revolution

                                Dulmage-Mendelsohn matrix decomposition in Python