Force elements at beginning and end of list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












15














How can I modify this list so that all p's appear at the beginning, the q's at the end, and the values in between are sorted alphabetically?



l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']


So I would like to have:



['p','p','a','b','c','d','f','g','n','t','z','q','q']









share|improve this question

















  • 10




    What have you tried that didn't work ?
    – bruno desthuilliers
    Dec 27 '18 at 16:20










  • Well I though of somehow sorting those items that anen't in ['p','q'], and then adding as many p and q as I found at the beginning and end. But thought that it could be done in a much easier way as it is clear now
    – Gerald
    Dec 27 '18 at 16:35
















15














How can I modify this list so that all p's appear at the beginning, the q's at the end, and the values in between are sorted alphabetically?



l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']


So I would like to have:



['p','p','a','b','c','d','f','g','n','t','z','q','q']









share|improve this question

















  • 10




    What have you tried that didn't work ?
    – bruno desthuilliers
    Dec 27 '18 at 16:20










  • Well I though of somehow sorting those items that anen't in ['p','q'], and then adding as many p and q as I found at the beginning and end. But thought that it could be done in a much easier way as it is clear now
    – Gerald
    Dec 27 '18 at 16:35














15












15








15


4





How can I modify this list so that all p's appear at the beginning, the q's at the end, and the values in between are sorted alphabetically?



l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']


So I would like to have:



['p','p','a','b','c','d','f','g','n','t','z','q','q']









share|improve this question













How can I modify this list so that all p's appear at the beginning, the q's at the end, and the values in between are sorted alphabetically?



l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']


So I would like to have:



['p','p','a','b','c','d','f','g','n','t','z','q','q']






python list sorting






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 27 '18 at 16:19









GeraldGerald

1606




1606







  • 10




    What have you tried that didn't work ?
    – bruno desthuilliers
    Dec 27 '18 at 16:20










  • Well I though of somehow sorting those items that anen't in ['p','q'], and then adding as many p and q as I found at the beginning and end. But thought that it could be done in a much easier way as it is clear now
    – Gerald
    Dec 27 '18 at 16:35













  • 10




    What have you tried that didn't work ?
    – bruno desthuilliers
    Dec 27 '18 at 16:20










  • Well I though of somehow sorting those items that anen't in ['p','q'], and then adding as many p and q as I found at the beginning and end. But thought that it could be done in a much easier way as it is clear now
    – Gerald
    Dec 27 '18 at 16:35








10




10




What have you tried that didn't work ?
– bruno desthuilliers
Dec 27 '18 at 16:20




What have you tried that didn't work ?
– bruno desthuilliers
Dec 27 '18 at 16:20












Well I though of somehow sorting those items that anen't in ['p','q'], and then adding as many p and q as I found at the beginning and end. But thought that it could be done in a much easier way as it is clear now
– Gerald
Dec 27 '18 at 16:35





Well I though of somehow sorting those items that anen't in ['p','q'], and then adding as many p and q as I found at the beginning and end. But thought that it could be done in a much easier way as it is clear now
– Gerald
Dec 27 '18 at 16:35













7 Answers
7






active

oldest

votes


















39














You can use sorted with the following key:



sorted(l, key = lambda s: (s!='p', s=='q', s))
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']



Explanation



To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda function defined in the key argument prior to making comparisons:



t = [(s!='p', s=='q', s) for s in pl]

print(t)
[(True, False, 'f'),
(True, False, 'g'),
(False, False, 'p'),
(True, False, 'a'),
(False, False, 'p'),
(True, False, 'c'),
(True, False, 'b'),
(True, True, 'q'),
(True, False, 'z'),
(True, False, 'n'),
(True, False, 'd'),
(True, False, 't'),
(True, True, 'q')]


This will then be the key to be used to sort the items in the list, as mentioned in the documentation:




The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.




So taking into account that False = 0 and True = 1, when this list of tuples is sorted the result will be the following:



sorted(t)
[(False, False, 'p'),
(False, False, 'p'),
(True, False, 'a'),
(True, False, 'b'),
(True, False, 'c'),
(True, False, 'd'),
(True, False, 'f'),
(True, False, 'g'),
(True, False, 'n'),
(True, False, 't'),
(True, False, 'z'),
(True, True, 'q'),
(True, True, 'q')]





share|improve this answer


















  • 3




    Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
    – Scott Boston
    Dec 27 '18 at 16:24







  • 2




    @ScottBoston no, it returns a (bool, bool, str) tuple
    – juanpa.arrivillaga
    Dec 27 '18 at 16:26






  • 3




    So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
    – yatu
    Dec 27 '18 at 16:27






  • 2




    @nixon Ah!!! The light bulb just turned on. Great!
    – Scott Boston
    Dec 27 '18 at 16:28







  • 1




    For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
    – Scott Boston
    Dec 27 '18 at 16:33


















14














One idea is to use a priority dictionary with a custom function. This is naturally extendable should you wish to include additional criteria.



L = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

def sort_func(x):
priority = 'p': 0, 'q': 2
return priority.get(x, 1), x

res = sorted(L, key=sort_func)

print(res)

['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





share|improve this answer




























    11














    Use the key parameter in sorted:



    l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

    def key(c):
    if c == 'q':
    return (2, c)
    elif c == 'p':
    return (0, c)
    return (1, c)


    result = sorted(l, key=key)
    print(result)


    Output



    ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





    share|improve this answer




























      4














      You can find all p and q elements, filter the original list, and then sort:



      l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
      _ps, _qs = [i for i in l if i == 'p'], [i for i in l if i == 'q']
      new_l = _ps+sorted(filter(lambda x:x not in 'q', 'p', l))+_qs


      Output:



      ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





      share|improve this answer




















      • If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
        – pault
        Dec 27 '18 at 16:26



















      4














      Just define an appropriate key function:



      >>> def _key(x):
      ... if x == 'p':
      ... return -1
      ... elif x == 'q':
      ... return float('inf')
      ... else:
      ... return ord(x)
      ...
      >>> l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
      >>> sorted(l, key=_key)
      ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']


      Note, every character is mapped to an integer >= 0, so we can just rely on ord, and since -1 will always be less than anything returned by ord, we can use that for p, and for q, we can use infinity, so it will be alway greater than something returned by ord.






      share|improve this answer






























        2














        You could also store you front, middle and ends in a collections.defaultdict(), then just add all three lists at the end:



        from collections import defaultdict

        l = ["f", "g", "p", "a", "p", "c", "b", "q", "z", "n", "d", "t", "q"]

        keys = "p": "front", "q": "end"

        d = defaultdict(list)
        for item in l:
        d[keys.get(item, "middle")].append(item)

        print(d["front"] + sorted(d["middle"]) + d["end"])
        # ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





        share|improve this answer






























          1














          Solution to this question is:



          1. First find all p and q elements in list.

          2. Filter the original list.

          3. Then, finally sort the list.


          list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
          noOfPs = [i for i in l if i == 'p'];
          noOfQs = [i for i in l if i == 'q'];
          resultList= noOfPs + sorted(filter(lambda x:x not in 'q', 'p', l))+ noOfQs





          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%2f53947928%2fforce-elements-at-beginning-and-end-of-list%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            39














            You can use sorted with the following key:



            sorted(l, key = lambda s: (s!='p', s=='q', s))
            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']



            Explanation



            To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda function defined in the key argument prior to making comparisons:



            t = [(s!='p', s=='q', s) for s in pl]

            print(t)
            [(True, False, 'f'),
            (True, False, 'g'),
            (False, False, 'p'),
            (True, False, 'a'),
            (False, False, 'p'),
            (True, False, 'c'),
            (True, False, 'b'),
            (True, True, 'q'),
            (True, False, 'z'),
            (True, False, 'n'),
            (True, False, 'd'),
            (True, False, 't'),
            (True, True, 'q')]


            This will then be the key to be used to sort the items in the list, as mentioned in the documentation:




            The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.




            So taking into account that False = 0 and True = 1, when this list of tuples is sorted the result will be the following:



            sorted(t)
            [(False, False, 'p'),
            (False, False, 'p'),
            (True, False, 'a'),
            (True, False, 'b'),
            (True, False, 'c'),
            (True, False, 'd'),
            (True, False, 'f'),
            (True, False, 'g'),
            (True, False, 'n'),
            (True, False, 't'),
            (True, False, 'z'),
            (True, True, 'q'),
            (True, True, 'q')]





            share|improve this answer


















            • 3




              Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
              – Scott Boston
              Dec 27 '18 at 16:24







            • 2




              @ScottBoston no, it returns a (bool, bool, str) tuple
              – juanpa.arrivillaga
              Dec 27 '18 at 16:26






            • 3




              So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
              – yatu
              Dec 27 '18 at 16:27






            • 2




              @nixon Ah!!! The light bulb just turned on. Great!
              – Scott Boston
              Dec 27 '18 at 16:28







            • 1




              For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
              – Scott Boston
              Dec 27 '18 at 16:33















            39














            You can use sorted with the following key:



            sorted(l, key = lambda s: (s!='p', s=='q', s))
            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']



            Explanation



            To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda function defined in the key argument prior to making comparisons:



            t = [(s!='p', s=='q', s) for s in pl]

            print(t)
            [(True, False, 'f'),
            (True, False, 'g'),
            (False, False, 'p'),
            (True, False, 'a'),
            (False, False, 'p'),
            (True, False, 'c'),
            (True, False, 'b'),
            (True, True, 'q'),
            (True, False, 'z'),
            (True, False, 'n'),
            (True, False, 'd'),
            (True, False, 't'),
            (True, True, 'q')]


            This will then be the key to be used to sort the items in the list, as mentioned in the documentation:




            The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.




            So taking into account that False = 0 and True = 1, when this list of tuples is sorted the result will be the following:



            sorted(t)
            [(False, False, 'p'),
            (False, False, 'p'),
            (True, False, 'a'),
            (True, False, 'b'),
            (True, False, 'c'),
            (True, False, 'd'),
            (True, False, 'f'),
            (True, False, 'g'),
            (True, False, 'n'),
            (True, False, 't'),
            (True, False, 'z'),
            (True, True, 'q'),
            (True, True, 'q')]





            share|improve this answer


















            • 3




              Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
              – Scott Boston
              Dec 27 '18 at 16:24







            • 2




              @ScottBoston no, it returns a (bool, bool, str) tuple
              – juanpa.arrivillaga
              Dec 27 '18 at 16:26






            • 3




              So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
              – yatu
              Dec 27 '18 at 16:27






            • 2




              @nixon Ah!!! The light bulb just turned on. Great!
              – Scott Boston
              Dec 27 '18 at 16:28







            • 1




              For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
              – Scott Boston
              Dec 27 '18 at 16:33













            39












            39








            39






            You can use sorted with the following key:



            sorted(l, key = lambda s: (s!='p', s=='q', s))
            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']



            Explanation



            To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda function defined in the key argument prior to making comparisons:



            t = [(s!='p', s=='q', s) for s in pl]

            print(t)
            [(True, False, 'f'),
            (True, False, 'g'),
            (False, False, 'p'),
            (True, False, 'a'),
            (False, False, 'p'),
            (True, False, 'c'),
            (True, False, 'b'),
            (True, True, 'q'),
            (True, False, 'z'),
            (True, False, 'n'),
            (True, False, 'd'),
            (True, False, 't'),
            (True, True, 'q')]


            This will then be the key to be used to sort the items in the list, as mentioned in the documentation:




            The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.




            So taking into account that False = 0 and True = 1, when this list of tuples is sorted the result will be the following:



            sorted(t)
            [(False, False, 'p'),
            (False, False, 'p'),
            (True, False, 'a'),
            (True, False, 'b'),
            (True, False, 'c'),
            (True, False, 'd'),
            (True, False, 'f'),
            (True, False, 'g'),
            (True, False, 'n'),
            (True, False, 't'),
            (True, False, 'z'),
            (True, True, 'q'),
            (True, True, 'q')]





            share|improve this answer














            You can use sorted with the following key:



            sorted(l, key = lambda s: (s!='p', s=='q', s))
            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']



            Explanation



            To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda function defined in the key argument prior to making comparisons:



            t = [(s!='p', s=='q', s) for s in pl]

            print(t)
            [(True, False, 'f'),
            (True, False, 'g'),
            (False, False, 'p'),
            (True, False, 'a'),
            (False, False, 'p'),
            (True, False, 'c'),
            (True, False, 'b'),
            (True, True, 'q'),
            (True, False, 'z'),
            (True, False, 'n'),
            (True, False, 'd'),
            (True, False, 't'),
            (True, True, 'q')]


            This will then be the key to be used to sort the items in the list, as mentioned in the documentation:




            The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.




            So taking into account that False = 0 and True = 1, when this list of tuples is sorted the result will be the following:



            sorted(t)
            [(False, False, 'p'),
            (False, False, 'p'),
            (True, False, 'a'),
            (True, False, 'b'),
            (True, False, 'c'),
            (True, False, 'd'),
            (True, False, 'f'),
            (True, False, 'g'),
            (True, False, 'n'),
            (True, False, 't'),
            (True, False, 'z'),
            (True, True, 'q'),
            (True, True, 'q')]






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 3 at 0:03

























            answered Dec 27 '18 at 16:21









            yatuyatu

            5,8501524




            5,8501524







            • 3




              Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
              – Scott Boston
              Dec 27 '18 at 16:24







            • 2




              @ScottBoston no, it returns a (bool, bool, str) tuple
              – juanpa.arrivillaga
              Dec 27 '18 at 16:26






            • 3




              So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
              – yatu
              Dec 27 '18 at 16:27






            • 2




              @nixon Ah!!! The light bulb just turned on. Great!
              – Scott Boston
              Dec 27 '18 at 16:28







            • 1




              For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
              – Scott Boston
              Dec 27 '18 at 16:33












            • 3




              Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
              – Scott Boston
              Dec 27 '18 at 16:24







            • 2




              @ScottBoston no, it returns a (bool, bool, str) tuple
              – juanpa.arrivillaga
              Dec 27 '18 at 16:26






            • 3




              So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
              – yatu
              Dec 27 '18 at 16:27






            • 2




              @nixon Ah!!! The light bulb just turned on. Great!
              – Scott Boston
              Dec 27 '18 at 16:28







            • 1




              For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
              – Scott Boston
              Dec 27 '18 at 16:33







            3




            3




            Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
            – Scott Boston
            Dec 27 '18 at 16:24





            Now, this is pretty cool. Can you explain a bit? sorted sorts True < characters < False?
            – Scott Boston
            Dec 27 '18 at 16:24





            2




            2




            @ScottBoston no, it returns a (bool, bool, str) tuple
            – juanpa.arrivillaga
            Dec 27 '18 at 16:26




            @ScottBoston no, it returns a (bool, bool, str) tuple
            – juanpa.arrivillaga
            Dec 27 '18 at 16:26




            3




            3




            So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
            – yatu
            Dec 27 '18 at 16:27




            So (False, False) comes first and (True,True) in the end. In between there will be (True,False)
            – yatu
            Dec 27 '18 at 16:27




            2




            2




            @nixon Ah!!! The light bulb just turned on. Great!
            – Scott Boston
            Dec 27 '18 at 16:28





            @nixon Ah!!! The light bulb just turned on. Great!
            – Scott Boston
            Dec 27 '18 at 16:28





            1




            1




            For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
            – Scott Boston
            Dec 27 '18 at 16:33




            For those of you who need this sorted([(s!='p', s=='q', s) for s in l]) is a great visual of what is going on.
            – Scott Boston
            Dec 27 '18 at 16:33













            14














            One idea is to use a priority dictionary with a custom function. This is naturally extendable should you wish to include additional criteria.



            L = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

            def sort_func(x):
            priority = 'p': 0, 'q': 2
            return priority.get(x, 1), x

            res = sorted(L, key=sort_func)

            print(res)

            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





            share|improve this answer

























              14














              One idea is to use a priority dictionary with a custom function. This is naturally extendable should you wish to include additional criteria.



              L = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

              def sort_func(x):
              priority = 'p': 0, 'q': 2
              return priority.get(x, 1), x

              res = sorted(L, key=sort_func)

              print(res)

              ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





              share|improve this answer























                14












                14








                14






                One idea is to use a priority dictionary with a custom function. This is naturally extendable should you wish to include additional criteria.



                L = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

                def sort_func(x):
                priority = 'p': 0, 'q': 2
                return priority.get(x, 1), x

                res = sorted(L, key=sort_func)

                print(res)

                ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                share|improve this answer












                One idea is to use a priority dictionary with a custom function. This is naturally extendable should you wish to include additional criteria.



                L = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

                def sort_func(x):
                priority = 'p': 0, 'q': 2
                return priority.get(x, 1), x

                res = sorted(L, key=sort_func)

                print(res)

                ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 27 '18 at 16:22









                jppjpp

                93.5k2054104




                93.5k2054104





















                    11














                    Use the key parameter in sorted:



                    l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

                    def key(c):
                    if c == 'q':
                    return (2, c)
                    elif c == 'p':
                    return (0, c)
                    return (1, c)


                    result = sorted(l, key=key)
                    print(result)


                    Output



                    ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                    share|improve this answer

























                      11














                      Use the key parameter in sorted:



                      l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

                      def key(c):
                      if c == 'q':
                      return (2, c)
                      elif c == 'p':
                      return (0, c)
                      return (1, c)


                      result = sorted(l, key=key)
                      print(result)


                      Output



                      ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                      share|improve this answer























                        11












                        11








                        11






                        Use the key parameter in sorted:



                        l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

                        def key(c):
                        if c == 'q':
                        return (2, c)
                        elif c == 'p':
                        return (0, c)
                        return (1, c)


                        result = sorted(l, key=key)
                        print(result)


                        Output



                        ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                        share|improve this answer












                        Use the key parameter in sorted:



                        l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']

                        def key(c):
                        if c == 'q':
                        return (2, c)
                        elif c == 'p':
                        return (0, c)
                        return (1, c)


                        result = sorted(l, key=key)
                        print(result)


                        Output



                        ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 27 '18 at 16:21









                        Daniel MesejoDaniel Mesejo

                        14.9k21028




                        14.9k21028





















                            4














                            You can find all p and q elements, filter the original list, and then sort:



                            l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                            _ps, _qs = [i for i in l if i == 'p'], [i for i in l if i == 'q']
                            new_l = _ps+sorted(filter(lambda x:x not in 'q', 'p', l))+_qs


                            Output:



                            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                            share|improve this answer




















                            • If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
                              – pault
                              Dec 27 '18 at 16:26
















                            4














                            You can find all p and q elements, filter the original list, and then sort:



                            l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                            _ps, _qs = [i for i in l if i == 'p'], [i for i in l if i == 'q']
                            new_l = _ps+sorted(filter(lambda x:x not in 'q', 'p', l))+_qs


                            Output:



                            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                            share|improve this answer




















                            • If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
                              – pault
                              Dec 27 '18 at 16:26














                            4












                            4








                            4






                            You can find all p and q elements, filter the original list, and then sort:



                            l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                            _ps, _qs = [i for i in l if i == 'p'], [i for i in l if i == 'q']
                            new_l = _ps+sorted(filter(lambda x:x not in 'q', 'p', l))+_qs


                            Output:



                            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                            share|improve this answer












                            You can find all p and q elements, filter the original list, and then sort:



                            l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                            _ps, _qs = [i for i in l if i == 'p'], [i for i in l if i == 'q']
                            new_l = _ps+sorted(filter(lambda x:x not in 'q', 'p', l))+_qs


                            Output:



                            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 27 '18 at 16:22









                            Ajax1234Ajax1234

                            40.6k42653




                            40.6k42653











                            • If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
                              – pault
                              Dec 27 '18 at 16:26

















                            • If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
                              – pault
                              Dec 27 '18 at 16:26
















                            If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
                            – pault
                            Dec 27 '18 at 16:26





                            If you're going to do it this way, you can also just count the ps and qs: ['p']*l.count('p') + sorted(filter('q', 'p'.isdisjoint, l)) + ['q']*l.count('q') which is the same time complexity. Edit: You can get rid of the lambda too.
                            – pault
                            Dec 27 '18 at 16:26












                            4














                            Just define an appropriate key function:



                            >>> def _key(x):
                            ... if x == 'p':
                            ... return -1
                            ... elif x == 'q':
                            ... return float('inf')
                            ... else:
                            ... return ord(x)
                            ...
                            >>> l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                            >>> sorted(l, key=_key)
                            ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']


                            Note, every character is mapped to an integer >= 0, so we can just rely on ord, and since -1 will always be less than anything returned by ord, we can use that for p, and for q, we can use infinity, so it will be alway greater than something returned by ord.






                            share|improve this answer



























                              4














                              Just define an appropriate key function:



                              >>> def _key(x):
                              ... if x == 'p':
                              ... return -1
                              ... elif x == 'q':
                              ... return float('inf')
                              ... else:
                              ... return ord(x)
                              ...
                              >>> l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                              >>> sorted(l, key=_key)
                              ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']


                              Note, every character is mapped to an integer >= 0, so we can just rely on ord, and since -1 will always be less than anything returned by ord, we can use that for p, and for q, we can use infinity, so it will be alway greater than something returned by ord.






                              share|improve this answer

























                                4












                                4








                                4






                                Just define an appropriate key function:



                                >>> def _key(x):
                                ... if x == 'p':
                                ... return -1
                                ... elif x == 'q':
                                ... return float('inf')
                                ... else:
                                ... return ord(x)
                                ...
                                >>> l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                                >>> sorted(l, key=_key)
                                ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']


                                Note, every character is mapped to an integer >= 0, so we can just rely on ord, and since -1 will always be less than anything returned by ord, we can use that for p, and for q, we can use infinity, so it will be alway greater than something returned by ord.






                                share|improve this answer














                                Just define an appropriate key function:



                                >>> def _key(x):
                                ... if x == 'p':
                                ... return -1
                                ... elif x == 'q':
                                ... return float('inf')
                                ... else:
                                ... return ord(x)
                                ...
                                >>> l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
                                >>> sorted(l, key=_key)
                                ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']


                                Note, every character is mapped to an integer >= 0, so we can just rely on ord, and since -1 will always be less than anything returned by ord, we can use that for p, and for q, we can use infinity, so it will be alway greater than something returned by ord.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Dec 27 '18 at 16:24

























                                answered Dec 27 '18 at 16:22









                                juanpa.arrivillagajuanpa.arrivillaga

                                37.4k33572




                                37.4k33572





















                                    2














                                    You could also store you front, middle and ends in a collections.defaultdict(), then just add all three lists at the end:



                                    from collections import defaultdict

                                    l = ["f", "g", "p", "a", "p", "c", "b", "q", "z", "n", "d", "t", "q"]

                                    keys = "p": "front", "q": "end"

                                    d = defaultdict(list)
                                    for item in l:
                                    d[keys.get(item, "middle")].append(item)

                                    print(d["front"] + sorted(d["middle"]) + d["end"])
                                    # ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                                    share|improve this answer



























                                      2














                                      You could also store you front, middle and ends in a collections.defaultdict(), then just add all three lists at the end:



                                      from collections import defaultdict

                                      l = ["f", "g", "p", "a", "p", "c", "b", "q", "z", "n", "d", "t", "q"]

                                      keys = "p": "front", "q": "end"

                                      d = defaultdict(list)
                                      for item in l:
                                      d[keys.get(item, "middle")].append(item)

                                      print(d["front"] + sorted(d["middle"]) + d["end"])
                                      # ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                                      share|improve this answer

























                                        2












                                        2








                                        2






                                        You could also store you front, middle and ends in a collections.defaultdict(), then just add all three lists at the end:



                                        from collections import defaultdict

                                        l = ["f", "g", "p", "a", "p", "c", "b", "q", "z", "n", "d", "t", "q"]

                                        keys = "p": "front", "q": "end"

                                        d = defaultdict(list)
                                        for item in l:
                                        d[keys.get(item, "middle")].append(item)

                                        print(d["front"] + sorted(d["middle"]) + d["end"])
                                        # ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']





                                        share|improve this answer














                                        You could also store you front, middle and ends in a collections.defaultdict(), then just add all three lists at the end:



                                        from collections import defaultdict

                                        l = ["f", "g", "p", "a", "p", "c", "b", "q", "z", "n", "d", "t", "q"]

                                        keys = "p": "front", "q": "end"

                                        d = defaultdict(list)
                                        for item in l:
                                        d[keys.get(item, "middle")].append(item)

                                        print(d["front"] + sorted(d["middle"]) + d["end"])
                                        # ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Dec 30 '18 at 2:33

























                                        answered Dec 27 '18 at 16:47









                                        RoadRunnerRoadRunner

                                        11k31340




                                        11k31340





















                                            1














                                            Solution to this question is:



                                            1. First find all p and q elements in list.

                                            2. Filter the original list.

                                            3. Then, finally sort the list.


                                            list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
                                            noOfPs = [i for i in l if i == 'p'];
                                            noOfQs = [i for i in l if i == 'q'];
                                            resultList= noOfPs + sorted(filter(lambda x:x not in 'q', 'p', l))+ noOfQs





                                            share|improve this answer



























                                              1














                                              Solution to this question is:



                                              1. First find all p and q elements in list.

                                              2. Filter the original list.

                                              3. Then, finally sort the list.


                                              list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
                                              noOfPs = [i for i in l if i == 'p'];
                                              noOfQs = [i for i in l if i == 'q'];
                                              resultList= noOfPs + sorted(filter(lambda x:x not in 'q', 'p', l))+ noOfQs





                                              share|improve this answer

























                                                1












                                                1








                                                1






                                                Solution to this question is:



                                                1. First find all p and q elements in list.

                                                2. Filter the original list.

                                                3. Then, finally sort the list.


                                                list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
                                                noOfPs = [i for i in l if i == 'p'];
                                                noOfQs = [i for i in l if i == 'q'];
                                                resultList= noOfPs + sorted(filter(lambda x:x not in 'q', 'p', l))+ noOfQs





                                                share|improve this answer














                                                Solution to this question is:



                                                1. First find all p and q elements in list.

                                                2. Filter the original list.

                                                3. Then, finally sort the list.


                                                list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
                                                noOfPs = [i for i in l if i == 'p'];
                                                noOfQs = [i for i in l if i == 'q'];
                                                resultList= noOfPs + sorted(filter(lambda x:x not in 'q', 'p', l))+ noOfQs






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Dec 28 '18 at 16:18









                                                pushkin

                                                3,979112651




                                                3,979112651










                                                answered Dec 28 '18 at 12:03









                                                Sagar P. GhagareSagar P. Ghagare

                                                1




                                                1



























                                                    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.





                                                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                    Please pay close attention to the following guidance:


                                                    • 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%2f53947928%2fforce-elements-at-beginning-and-end-of-list%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

                                                    How to check contact read email or not when send email to Individual?

                                                    Bahrain

                                                    Postfix configuration issue with fips on centos 7; mailgun relay