How to numerically sort list of strings containing numbers?












2















f1 = open("leader")
lines = f1.readlines()
lines.sort(key=int, reverse=True)
f1.close()
print(lines)


with external file values:



345345:player7
435:zo
345:name
23:hello
1231:football


this is to sort them so that the integers are sorted not the names










share|improve this question

























  • i also need help on adding other values without deleting everything in the external file

    – leo
    Jan 2 at 19:16











  • You will need to open the file using 'a' which stands for append. f1 = open("leader", 'a')

    – hqkhan
    Jan 2 at 19:22











  • It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Please see How to Ask and The perfect question. It is unclear if you have problems putting data into datastrucures, reading data from file, sorting data, inserting data (dicts are unordered or insertordersorted- not by numbers) or if you can not save data.

    – Patrick Artner
    Jan 2 at 19:24











  • What you most probably want is this: How to create a highscore in python

    – Patrick Artner
    Jan 2 at 19:26
















2















f1 = open("leader")
lines = f1.readlines()
lines.sort(key=int, reverse=True)
f1.close()
print(lines)


with external file values:



345345:player7
435:zo
345:name
23:hello
1231:football


this is to sort them so that the integers are sorted not the names










share|improve this question

























  • i also need help on adding other values without deleting everything in the external file

    – leo
    Jan 2 at 19:16











  • You will need to open the file using 'a' which stands for append. f1 = open("leader", 'a')

    – hqkhan
    Jan 2 at 19:22











  • It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Please see How to Ask and The perfect question. It is unclear if you have problems putting data into datastrucures, reading data from file, sorting data, inserting data (dicts are unordered or insertordersorted- not by numbers) or if you can not save data.

    – Patrick Artner
    Jan 2 at 19:24











  • What you most probably want is this: How to create a highscore in python

    – Patrick Artner
    Jan 2 at 19:26














2












2








2








f1 = open("leader")
lines = f1.readlines()
lines.sort(key=int, reverse=True)
f1.close()
print(lines)


with external file values:



345345:player7
435:zo
345:name
23:hello
1231:football


this is to sort them so that the integers are sorted not the names










share|improve this question
















f1 = open("leader")
lines = f1.readlines()
lines.sort(key=int, reverse=True)
f1.close()
print(lines)


with external file values:



345345:player7
435:zo
345:name
23:hello
1231:football


this is to sort them so that the integers are sorted not the names







python sorting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 21:59









nabster

60111026




60111026










asked Jan 2 at 19:15









leoleo

163




163













  • i also need help on adding other values without deleting everything in the external file

    – leo
    Jan 2 at 19:16











  • You will need to open the file using 'a' which stands for append. f1 = open("leader", 'a')

    – hqkhan
    Jan 2 at 19:22











  • It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Please see How to Ask and The perfect question. It is unclear if you have problems putting data into datastrucures, reading data from file, sorting data, inserting data (dicts are unordered or insertordersorted- not by numbers) or if you can not save data.

    – Patrick Artner
    Jan 2 at 19:24











  • What you most probably want is this: How to create a highscore in python

    – Patrick Artner
    Jan 2 at 19:26



















  • i also need help on adding other values without deleting everything in the external file

    – leo
    Jan 2 at 19:16











  • You will need to open the file using 'a' which stands for append. f1 = open("leader", 'a')

    – hqkhan
    Jan 2 at 19:22











  • It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Please see How to Ask and The perfect question. It is unclear if you have problems putting data into datastrucures, reading data from file, sorting data, inserting data (dicts are unordered or insertordersorted- not by numbers) or if you can not save data.

    – Patrick Artner
    Jan 2 at 19:24











  • What you most probably want is this: How to create a highscore in python

    – Patrick Artner
    Jan 2 at 19:26

















i also need help on adding other values without deleting everything in the external file

– leo
Jan 2 at 19:16





i also need help on adding other values without deleting everything in the external file

– leo
Jan 2 at 19:16













You will need to open the file using 'a' which stands for append. f1 = open("leader", 'a')

– hqkhan
Jan 2 at 19:22





You will need to open the file using 'a' which stands for append. f1 = open("leader", 'a')

– hqkhan
Jan 2 at 19:22













It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Please see How to Ask and The perfect question. It is unclear if you have problems putting data into datastrucures, reading data from file, sorting data, inserting data (dicts are unordered or insertordersorted- not by numbers) or if you can not save data.

– Patrick Artner
Jan 2 at 19:24





It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Please see How to Ask and The perfect question. It is unclear if you have problems putting data into datastrucures, reading data from file, sorting data, inserting data (dicts are unordered or insertordersorted- not by numbers) or if you can not save data.

– Patrick Artner
Jan 2 at 19:24













What you most probably want is this: How to create a highscore in python

– Patrick Artner
Jan 2 at 19:26





What you most probably want is this: How to create a highscore in python

– Patrick Artner
Jan 2 at 19:26












3 Answers
3






active

oldest

votes


















0














Try this:
(helpful if you are still reading from a file)



with open('leader.txt', mode = 'r') as f1:
data = f1.readlines()
# end with
keys = {}
output =
for s in data:
num, value = s.split(sep=':')
if keys.get(int(num), False):
keys[int(num)].append(value)
else:
keys[int(num)] = [value]
for num in sorted(keys):
for i in keys[num]:
output.append((num, i))
for num, value in output:
print(f'{num}: {value}')





share|improve this answer





















  • 1





    I think your num, value = int(s.split(sep=':')) will throw an error

    – hqkhan
    Jan 2 at 19:30











  • if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

    – Patrick Artner
    Jan 2 at 19:31











  • sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

    – GeeTransit
    Jan 2 at 19:34



















4














IIUC:



l = ['345345:player7',
'435:zo',
'345:name',
'23:hello',
'1231:football']

sorted(l, key=lambda x: int(x.split(':')[0]))


Output:



['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']





share|improve this answer





















  • 1





    Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

    – hqkhan
    Jan 2 at 19:23






  • 2





    well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

    – Jean-François Fabre
    Jan 2 at 19:23








  • 1





    Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

    – hqkhan
    Jan 2 at 19:24











  • I've updated the solution.

    – Scott Boston
    Jan 2 at 19:25











  • however this does not work as it has to be outputted from an external file and outputs this:

    – leo
    Jan 3 at 11:41



















4














The sort key should do: "split once, convert to integer". Not converting to integer fails because then lexicographical compare is used and in that case "10" < "2", not that you want.



l = ['345345:player7',
'435:zo',
'345:name',
'23:hello',
'1231:football']

result = sorted(l, key=lambda x: int(x.split(':',1)[0]))


result:



['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']


that doesn't handle the tiebreaker where numbers are equal. A slightly more complex sort key would be required (but still doable). In that case, drop lambda and create a real function so you can perform split once & unpack to convert only the first part to integer:



def sortfunc(x):
number,rest = x.split(':',1)
return int(number),rest

result = sorted(l, key=sortfunc)





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',
    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%2f54011949%2fhow-to-numerically-sort-list-of-strings-containing-numbers%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Try this:
    (helpful if you are still reading from a file)



    with open('leader.txt', mode = 'r') as f1:
    data = f1.readlines()
    # end with
    keys = {}
    output =
    for s in data:
    num, value = s.split(sep=':')
    if keys.get(int(num), False):
    keys[int(num)].append(value)
    else:
    keys[int(num)] = [value]
    for num in sorted(keys):
    for i in keys[num]:
    output.append((num, i))
    for num, value in output:
    print(f'{num}: {value}')





    share|improve this answer





















    • 1





      I think your num, value = int(s.split(sep=':')) will throw an error

      – hqkhan
      Jan 2 at 19:30











    • if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

      – Patrick Artner
      Jan 2 at 19:31











    • sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

      – GeeTransit
      Jan 2 at 19:34
















    0














    Try this:
    (helpful if you are still reading from a file)



    with open('leader.txt', mode = 'r') as f1:
    data = f1.readlines()
    # end with
    keys = {}
    output =
    for s in data:
    num, value = s.split(sep=':')
    if keys.get(int(num), False):
    keys[int(num)].append(value)
    else:
    keys[int(num)] = [value]
    for num in sorted(keys):
    for i in keys[num]:
    output.append((num, i))
    for num, value in output:
    print(f'{num}: {value}')





    share|improve this answer





















    • 1





      I think your num, value = int(s.split(sep=':')) will throw an error

      – hqkhan
      Jan 2 at 19:30











    • if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

      – Patrick Artner
      Jan 2 at 19:31











    • sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

      – GeeTransit
      Jan 2 at 19:34














    0












    0








    0







    Try this:
    (helpful if you are still reading from a file)



    with open('leader.txt', mode = 'r') as f1:
    data = f1.readlines()
    # end with
    keys = {}
    output =
    for s in data:
    num, value = s.split(sep=':')
    if keys.get(int(num), False):
    keys[int(num)].append(value)
    else:
    keys[int(num)] = [value]
    for num in sorted(keys):
    for i in keys[num]:
    output.append((num, i))
    for num, value in output:
    print(f'{num}: {value}')





    share|improve this answer















    Try this:
    (helpful if you are still reading from a file)



    with open('leader.txt', mode = 'r') as f1:
    data = f1.readlines()
    # end with
    keys = {}
    output =
    for s in data:
    num, value = s.split(sep=':')
    if keys.get(int(num), False):
    keys[int(num)].append(value)
    else:
    keys[int(num)] = [value]
    for num in sorted(keys):
    for i in keys[num]:
    output.append((num, i))
    for num, value in output:
    print(f'{num}: {value}')






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 2 at 19:38

























    answered Jan 2 at 19:28









    GeeTransitGeeTransit

    694316




    694316








    • 1





      I think your num, value = int(s.split(sep=':')) will throw an error

      – hqkhan
      Jan 2 at 19:30











    • if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

      – Patrick Artner
      Jan 2 at 19:31











    • sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

      – GeeTransit
      Jan 2 at 19:34














    • 1





      I think your num, value = int(s.split(sep=':')) will throw an error

      – hqkhan
      Jan 2 at 19:30











    • if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

      – Patrick Artner
      Jan 2 at 19:31











    • sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

      – GeeTransit
      Jan 2 at 19:34








    1




    1





    I think your num, value = int(s.split(sep=':')) will throw an error

    – hqkhan
    Jan 2 at 19:30





    I think your num, value = int(s.split(sep=':')) will throw an error

    – hqkhan
    Jan 2 at 19:30













    if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

    – Patrick Artner
    Jan 2 at 19:31





    if 2 ppl have the same number, only the last will survive after you fix the ValueError from intergerparsing a list containt a number and a string-

    – Patrick Artner
    Jan 2 at 19:31













    sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

    – GeeTransit
    Jan 2 at 19:34





    sorry about the int around the list. wasn't careful haha... i'll fix the two people one number issue.

    – GeeTransit
    Jan 2 at 19:34













    4














    IIUC:



    l = ['345345:player7',
    '435:zo',
    '345:name',
    '23:hello',
    '1231:football']

    sorted(l, key=lambda x: int(x.split(':')[0]))


    Output:



    ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']





    share|improve this answer





















    • 1





      Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

      – hqkhan
      Jan 2 at 19:23






    • 2





      well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

      – Jean-François Fabre
      Jan 2 at 19:23








    • 1





      Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

      – hqkhan
      Jan 2 at 19:24











    • I've updated the solution.

      – Scott Boston
      Jan 2 at 19:25











    • however this does not work as it has to be outputted from an external file and outputs this:

      – leo
      Jan 3 at 11:41
















    4














    IIUC:



    l = ['345345:player7',
    '435:zo',
    '345:name',
    '23:hello',
    '1231:football']

    sorted(l, key=lambda x: int(x.split(':')[0]))


    Output:



    ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']





    share|improve this answer





















    • 1





      Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

      – hqkhan
      Jan 2 at 19:23






    • 2





      well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

      – Jean-François Fabre
      Jan 2 at 19:23








    • 1





      Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

      – hqkhan
      Jan 2 at 19:24











    • I've updated the solution.

      – Scott Boston
      Jan 2 at 19:25











    • however this does not work as it has to be outputted from an external file and outputs this:

      – leo
      Jan 3 at 11:41














    4












    4








    4







    IIUC:



    l = ['345345:player7',
    '435:zo',
    '345:name',
    '23:hello',
    '1231:football']

    sorted(l, key=lambda x: int(x.split(':')[0]))


    Output:



    ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']





    share|improve this answer















    IIUC:



    l = ['345345:player7',
    '435:zo',
    '345:name',
    '23:hello',
    '1231:football']

    sorted(l, key=lambda x: int(x.split(':')[0]))


    Output:



    ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 2 at 19:25

























    answered Jan 2 at 19:19









    Scott BostonScott Boston

    56.7k73158




    56.7k73158








    • 1





      Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

      – hqkhan
      Jan 2 at 19:23






    • 2





      well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

      – Jean-François Fabre
      Jan 2 at 19:23








    • 1





      Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

      – hqkhan
      Jan 2 at 19:24











    • I've updated the solution.

      – Scott Boston
      Jan 2 at 19:25











    • however this does not work as it has to be outputted from an external file and outputs this:

      – leo
      Jan 3 at 11:41














    • 1





      Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

      – hqkhan
      Jan 2 at 19:23






    • 2





      well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

      – Jean-François Fabre
      Jan 2 at 19:23








    • 1





      Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

      – hqkhan
      Jan 2 at 19:24











    • I've updated the solution.

      – Scott Boston
      Jan 2 at 19:25











    • however this does not work as it has to be outputted from an external file and outputs this:

      – leo
      Jan 3 at 11:41








    1




    1





    Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

    – hqkhan
    Jan 2 at 19:23





    Don't you need to parse the digits into int when sorting since OP mentioned sorting the numbers?

    – hqkhan
    Jan 2 at 19:23




    2




    2





    well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

    – Jean-François Fabre
    Jan 2 at 19:23







    well, it appears to work, but doesn't perform a numerical sort, just a lexicographical sort. 1231 should appear after 435 for instance.

    – Jean-François Fabre
    Jan 2 at 19:23






    1




    1





    Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

    – hqkhan
    Jan 2 at 19:24





    Right, it'll definitely not throw an error but I think OP wanted @Jean-FrançoisFabre's answer here.

    – hqkhan
    Jan 2 at 19:24













    I've updated the solution.

    – Scott Boston
    Jan 2 at 19:25





    I've updated the solution.

    – Scott Boston
    Jan 2 at 19:25













    however this does not work as it has to be outputted from an external file and outputs this:

    – leo
    Jan 3 at 11:41





    however this does not work as it has to be outputted from an external file and outputs this:

    – leo
    Jan 3 at 11:41











    4














    The sort key should do: "split once, convert to integer". Not converting to integer fails because then lexicographical compare is used and in that case "10" < "2", not that you want.



    l = ['345345:player7',
    '435:zo',
    '345:name',
    '23:hello',
    '1231:football']

    result = sorted(l, key=lambda x: int(x.split(':',1)[0]))


    result:



    ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']


    that doesn't handle the tiebreaker where numbers are equal. A slightly more complex sort key would be required (but still doable). In that case, drop lambda and create a real function so you can perform split once & unpack to convert only the first part to integer:



    def sortfunc(x):
    number,rest = x.split(':',1)
    return int(number),rest

    result = sorted(l, key=sortfunc)





    share|improve this answer






























      4














      The sort key should do: "split once, convert to integer". Not converting to integer fails because then lexicographical compare is used and in that case "10" < "2", not that you want.



      l = ['345345:player7',
      '435:zo',
      '345:name',
      '23:hello',
      '1231:football']

      result = sorted(l, key=lambda x: int(x.split(':',1)[0]))


      result:



      ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']


      that doesn't handle the tiebreaker where numbers are equal. A slightly more complex sort key would be required (but still doable). In that case, drop lambda and create a real function so you can perform split once & unpack to convert only the first part to integer:



      def sortfunc(x):
      number,rest = x.split(':',1)
      return int(number),rest

      result = sorted(l, key=sortfunc)





      share|improve this answer




























        4












        4








        4







        The sort key should do: "split once, convert to integer". Not converting to integer fails because then lexicographical compare is used and in that case "10" < "2", not that you want.



        l = ['345345:player7',
        '435:zo',
        '345:name',
        '23:hello',
        '1231:football']

        result = sorted(l, key=lambda x: int(x.split(':',1)[0]))


        result:



        ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']


        that doesn't handle the tiebreaker where numbers are equal. A slightly more complex sort key would be required (but still doable). In that case, drop lambda and create a real function so you can perform split once & unpack to convert only the first part to integer:



        def sortfunc(x):
        number,rest = x.split(':',1)
        return int(number),rest

        result = sorted(l, key=sortfunc)





        share|improve this answer















        The sort key should do: "split once, convert to integer". Not converting to integer fails because then lexicographical compare is used and in that case "10" < "2", not that you want.



        l = ['345345:player7',
        '435:zo',
        '345:name',
        '23:hello',
        '1231:football']

        result = sorted(l, key=lambda x: int(x.split(':',1)[0]))


        result:



        ['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']


        that doesn't handle the tiebreaker where numbers are equal. A slightly more complex sort key would be required (but still doable). In that case, drop lambda and create a real function so you can perform split once & unpack to convert only the first part to integer:



        def sortfunc(x):
        number,rest = x.split(':',1)
        return int(number),rest

        result = sorted(l, key=sortfunc)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 2 at 19:29

























        answered Jan 2 at 19:22









        Jean-François FabreJean-François Fabre

        106k957115




        106k957115






























            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%2f54011949%2fhow-to-numerically-sort-list-of-strings-containing-numbers%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

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas