python selective joining of list to get a string












0















Lets say I have a list in python like :



['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']


Is it possible to use list join to selectively add elements of a list. For example I add the full element0, but for other elements of the list I just add the last character(also I add the last character of element only if its length is3). so the string becomes:



"ann"+"e"+"f"+"r"+"a"+"n"+"k"= annefrank 


The last element is not added as its not of length 3.
I can solve this using for loop, but would like to know if there is any optimized pythonic way of doing this or using join.



Thank you in anticipation.
AIA










share|improve this question





























    0















    Lets say I have a list in python like :



    ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']


    Is it possible to use list join to selectively add elements of a list. For example I add the full element0, but for other elements of the list I just add the last character(also I add the last character of element only if its length is3). so the string becomes:



    "ann"+"e"+"f"+"r"+"a"+"n"+"k"= annefrank 


    The last element is not added as its not of length 3.
    I can solve this using for loop, but would like to know if there is any optimized pythonic way of doing this or using join.



    Thank you in anticipation.
    AIA










    share|improve this question



























      0












      0








      0








      Lets say I have a list in python like :



      ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']


      Is it possible to use list join to selectively add elements of a list. For example I add the full element0, but for other elements of the list I just add the last character(also I add the last character of element only if its length is3). so the string becomes:



      "ann"+"e"+"f"+"r"+"a"+"n"+"k"= annefrank 


      The last element is not added as its not of length 3.
      I can solve this using for loop, but would like to know if there is any optimized pythonic way of doing this or using join.



      Thank you in anticipation.
      AIA










      share|improve this question
















      Lets say I have a list in python like :



      ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']


      Is it possible to use list join to selectively add elements of a list. For example I add the full element0, but for other elements of the list I just add the last character(also I add the last character of element only if its length is3). so the string becomes:



      "ann"+"e"+"f"+"r"+"a"+"n"+"k"= annefrank 


      The last element is not added as its not of length 3.
      I can solve this using for loop, but would like to know if there is any optimized pythonic way of doing this or using join.



      Thank you in anticipation.
      AIA







      python-3.x list






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 19:44









      Franco Piccolo

      1,576712




      1,576712










      asked Nov 21 '18 at 16:31









      AIMCognitiveGurgaon BigDataAIMCognitiveGurgaon BigData

      124




      124
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Since you have certain requirements you need to apply some custom logic anyway, regardless of the paradigm that you choose.



          I would use Python's functional tools for filtering the sequence:



          import operator
          import functools

          seq = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']

          functools.reduce(operator.add, (map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))), seq[0])
          # gives annefrank


          The inner filter takes care of elements which are not of length 3, except the first element of the list. The map will return their last character and the reduce will apply add over them with first element of the list as the initial value.



          You can also do it with join if you prefer:



          seq[0]+''.join((map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))))
          # gives annefrank


          You can also merge the filter into the map:



          seq[0]+''.join((map(lambda x: x[-1] if len(x)==3 else '', seq[1:])))


          As you see there are many ways to achieve what you want to do. However I will prefer map and filter over looping over a sequence since they have highly optimized implementations.






          share|improve this answer


























          • Thanks a lot for the solution..

            – AIMCognitiveGurgaon BigData
            Nov 22 '18 at 14:13



















          0














          You could build a list of the third letter from each item in the list:



              mylist = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']
          thirdletters = [ x[2:3] for x in mylist ]


          (the final item in that new list will be an empty string because there is no third letter in 'nk') then collect those letters into a string by using join with an empty string as the filler:



              thirdstring = ''.join(thirdletters)


          and then finally add that string after the first two letters of the first item from the original list:



              result = mylist[0][:2] + thirdstring


          If that's too wordy, you can jam it all together into one statement:



              result = mylist[0][:2] + ''.join( [ x[2:3] for x in mylist ] )





          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%2f53416584%2fpython-selective-joining-of-list-to-get-a-string%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Since you have certain requirements you need to apply some custom logic anyway, regardless of the paradigm that you choose.



            I would use Python's functional tools for filtering the sequence:



            import operator
            import functools

            seq = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']

            functools.reduce(operator.add, (map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))), seq[0])
            # gives annefrank


            The inner filter takes care of elements which are not of length 3, except the first element of the list. The map will return their last character and the reduce will apply add over them with first element of the list as the initial value.



            You can also do it with join if you prefer:



            seq[0]+''.join((map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))))
            # gives annefrank


            You can also merge the filter into the map:



            seq[0]+''.join((map(lambda x: x[-1] if len(x)==3 else '', seq[1:])))


            As you see there are many ways to achieve what you want to do. However I will prefer map and filter over looping over a sequence since they have highly optimized implementations.






            share|improve this answer


























            • Thanks a lot for the solution..

              – AIMCognitiveGurgaon BigData
              Nov 22 '18 at 14:13
















            0














            Since you have certain requirements you need to apply some custom logic anyway, regardless of the paradigm that you choose.



            I would use Python's functional tools for filtering the sequence:



            import operator
            import functools

            seq = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']

            functools.reduce(operator.add, (map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))), seq[0])
            # gives annefrank


            The inner filter takes care of elements which are not of length 3, except the first element of the list. The map will return their last character and the reduce will apply add over them with first element of the list as the initial value.



            You can also do it with join if you prefer:



            seq[0]+''.join((map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))))
            # gives annefrank


            You can also merge the filter into the map:



            seq[0]+''.join((map(lambda x: x[-1] if len(x)==3 else '', seq[1:])))


            As you see there are many ways to achieve what you want to do. However I will prefer map and filter over looping over a sequence since they have highly optimized implementations.






            share|improve this answer


























            • Thanks a lot for the solution..

              – AIMCognitiveGurgaon BigData
              Nov 22 '18 at 14:13














            0












            0








            0







            Since you have certain requirements you need to apply some custom logic anyway, regardless of the paradigm that you choose.



            I would use Python's functional tools for filtering the sequence:



            import operator
            import functools

            seq = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']

            functools.reduce(operator.add, (map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))), seq[0])
            # gives annefrank


            The inner filter takes care of elements which are not of length 3, except the first element of the list. The map will return their last character and the reduce will apply add over them with first element of the list as the initial value.



            You can also do it with join if you prefer:



            seq[0]+''.join((map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))))
            # gives annefrank


            You can also merge the filter into the map:



            seq[0]+''.join((map(lambda x: x[-1] if len(x)==3 else '', seq[1:])))


            As you see there are many ways to achieve what you want to do. However I will prefer map and filter over looping over a sequence since they have highly optimized implementations.






            share|improve this answer















            Since you have certain requirements you need to apply some custom logic anyway, regardless of the paradigm that you choose.



            I would use Python's functional tools for filtering the sequence:



            import operator
            import functools

            seq = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']

            functools.reduce(operator.add, (map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))), seq[0])
            # gives annefrank


            The inner filter takes care of elements which are not of length 3, except the first element of the list. The map will return their last character and the reduce will apply add over them with first element of the list as the initial value.



            You can also do it with join if you prefer:



            seq[0]+''.join((map(lambda x: x[-1], filter(lambda x: len(x)==3, seq[1:]))))
            # gives annefrank


            You can also merge the filter into the map:



            seq[0]+''.join((map(lambda x: x[-1] if len(x)==3 else '', seq[1:])))


            As you see there are many ways to achieve what you want to do. However I will prefer map and filter over looping over a sequence since they have highly optimized implementations.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 '18 at 15:41

























            answered Nov 22 '18 at 9:39









            Mehdi SadeghiMehdi Sadeghi

            2,7451726




            2,7451726













            • Thanks a lot for the solution..

              – AIMCognitiveGurgaon BigData
              Nov 22 '18 at 14:13



















            • Thanks a lot for the solution..

              – AIMCognitiveGurgaon BigData
              Nov 22 '18 at 14:13

















            Thanks a lot for the solution..

            – AIMCognitiveGurgaon BigData
            Nov 22 '18 at 14:13





            Thanks a lot for the solution..

            – AIMCognitiveGurgaon BigData
            Nov 22 '18 at 14:13













            0














            You could build a list of the third letter from each item in the list:



                mylist = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']
            thirdletters = [ x[2:3] for x in mylist ]


            (the final item in that new list will be an empty string because there is no third letter in 'nk') then collect those letters into a string by using join with an empty string as the filler:



                thirdstring = ''.join(thirdletters)


            and then finally add that string after the first two letters of the first item from the original list:



                result = mylist[0][:2] + thirdstring


            If that's too wordy, you can jam it all together into one statement:



                result = mylist[0][:2] + ''.join( [ x[2:3] for x in mylist ] )





            share|improve this answer




























              0














              You could build a list of the third letter from each item in the list:



                  mylist = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']
              thirdletters = [ x[2:3] for x in mylist ]


              (the final item in that new list will be an empty string because there is no third letter in 'nk') then collect those letters into a string by using join with an empty string as the filler:



                  thirdstring = ''.join(thirdletters)


              and then finally add that string after the first two letters of the first item from the original list:



                  result = mylist[0][:2] + thirdstring


              If that's too wordy, you can jam it all together into one statement:



                  result = mylist[0][:2] + ''.join( [ x[2:3] for x in mylist ] )





              share|improve this answer


























                0












                0








                0







                You could build a list of the third letter from each item in the list:



                    mylist = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']
                thirdletters = [ x[2:3] for x in mylist ]


                (the final item in that new list will be an empty string because there is no third letter in 'nk') then collect those letters into a string by using join with an empty string as the filler:



                    thirdstring = ''.join(thirdletters)


                and then finally add that string after the first two letters of the first item from the original list:



                    result = mylist[0][:2] + thirdstring


                If that's too wordy, you can jam it all together into one statement:



                    result = mylist[0][:2] + ''.join( [ x[2:3] for x in mylist ] )





                share|improve this answer













                You could build a list of the third letter from each item in the list:



                    mylist = ['ann', 'nne', 'nef', 'efr', 'fra', 'ran', 'ank', 'nk']
                thirdletters = [ x[2:3] for x in mylist ]


                (the final item in that new list will be an empty string because there is no third letter in 'nk') then collect those letters into a string by using join with an empty string as the filler:



                    thirdstring = ''.join(thirdletters)


                and then finally add that string after the first two letters of the first item from the original list:



                    result = mylist[0][:2] + thirdstring


                If that's too wordy, you can jam it all together into one statement:



                    result = mylist[0][:2] + ''.join( [ x[2:3] for x in mylist ] )






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 '18 at 8:54









                ottomeisterottomeister

                2,39421117




                2,39421117






























                    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%2f53416584%2fpython-selective-joining-of-list-to-get-a-string%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

                    Paul Cézanne

                    UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

                    Angular material date-picker (MatDatepicker) auto completes the date on focus out