How to make a Python function that operates on two or more nested lists of the same shape?Convert two lists into a dictionaryHow can I safely create a nested directory?How do I return multiple values from a function?How can I make a time delay in Python?How to remove an element from a list by index?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How can I reverse a list in Python?

Why does it seem the best way to make a living is to invest in real estate?

GPLv3 forces us to make code available, but to who?

Could Boris Johnson face criminal charges for illegally proroguing Parliament?

What's the global, general word that stands for "center tone of a song"?

Can a passenger predict that an airline or a tour operator is about to go bankrupt?

How is this situation not a checkmate?

Why do Russians sometimes spell "жирный" (fatty) as "жырный"?

Why the first octet of a MAC address always end with a binary 0?

How closely correlated is culture to geography?

Would an object shot from earth fall into the sun?

Avoiding dust scattering when you drill

How to "Start as close to the end as possible", and why to do so?

Does Bank Manager's discretion still exist in Mortgage Lending

Would a horse be sufficient buffer to prevent injury when falling from a great height?

What are one's options when facing religious discrimination at the airport?

How to transcribe an arpeggiated 4-note chord to be playable on a violin?

SOQL injection vulnerability issue

Can I bring this power bank on board the aircraft?

Booting Ubuntu from USB drive on MSI motherboard -- EVERYTHING fails

Shell Sort, Insertion Sort, Bubble Sort, Selection Sort Algorithms (Python)

Sending mail to the Professor for PhD, after seeing his tweet

PhD Length: are shorter PhD degrees (from different countries) valued differently in other counter countries where PhD Is a longer process?

Do jackscrews suffer from blowdown?

What does "execute a hard copy" mean?



How to make a Python function that operates on two or more nested lists of the same shape?


Convert two lists into a dictionaryHow can I safely create a nested directory?How do I return multiple values from a function?How can I make a time delay in Python?How to remove an element from a list by index?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How can I reverse a list in Python?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









1















I would like to apply an arbitrary function to two or more nested lists of the same shape. For instance if my function is:



def add(a, b):
if "NULL" not in [a, b]:
return a + b
else:
return "NULL"


and my inputs are:



input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]


Then I would like the output to be



output = [[10, 10, "NULL"], [10, 10], [10, 10, 10, 10]]


The inputs will always be nested one level deep, but the outputs ideally should be anything (for instance it could be nested deeper if the function was a "concatenate(a, b)" function)










share|improve this question


























  • Will the lists only ever be nested one level deep?

    – Peter Collingridge
    Mar 28 at 21:08











  • @PeterCollingridge Yes, at least in the input stage (perhaps the output could be nested deeper depending on the function applied)

    – AAC
    Mar 28 at 21:24












  • If the lists are nested one level deep aways, why not [func(val) for val in list_of_lists] or event map(func, list_of_lists), it would simplify your function.

    – geckos
    Mar 28 at 21:30

















1















I would like to apply an arbitrary function to two or more nested lists of the same shape. For instance if my function is:



def add(a, b):
if "NULL" not in [a, b]:
return a + b
else:
return "NULL"


and my inputs are:



input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]


Then I would like the output to be



output = [[10, 10, "NULL"], [10, 10], [10, 10, 10, 10]]


The inputs will always be nested one level deep, but the outputs ideally should be anything (for instance it could be nested deeper if the function was a "concatenate(a, b)" function)










share|improve this question


























  • Will the lists only ever be nested one level deep?

    – Peter Collingridge
    Mar 28 at 21:08











  • @PeterCollingridge Yes, at least in the input stage (perhaps the output could be nested deeper depending on the function applied)

    – AAC
    Mar 28 at 21:24












  • If the lists are nested one level deep aways, why not [func(val) for val in list_of_lists] or event map(func, list_of_lists), it would simplify your function.

    – geckos
    Mar 28 at 21:30













1












1








1








I would like to apply an arbitrary function to two or more nested lists of the same shape. For instance if my function is:



def add(a, b):
if "NULL" not in [a, b]:
return a + b
else:
return "NULL"


and my inputs are:



input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]


Then I would like the output to be



output = [[10, 10, "NULL"], [10, 10], [10, 10, 10, 10]]


The inputs will always be nested one level deep, but the outputs ideally should be anything (for instance it could be nested deeper if the function was a "concatenate(a, b)" function)










share|improve this question
















I would like to apply an arbitrary function to two or more nested lists of the same shape. For instance if my function is:



def add(a, b):
if "NULL" not in [a, b]:
return a + b
else:
return "NULL"


and my inputs are:



input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]


Then I would like the output to be



output = [[10, 10, "NULL"], [10, 10], [10, 10, 10, 10]]


The inputs will always be nested one level deep, but the outputs ideally should be anything (for instance it could be nested deeper if the function was a "concatenate(a, b)" function)







python list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 21:30







AAC

















asked Mar 28 at 20:54









AACAAC

2161 silver badge9 bronze badges




2161 silver badge9 bronze badges















  • Will the lists only ever be nested one level deep?

    – Peter Collingridge
    Mar 28 at 21:08











  • @PeterCollingridge Yes, at least in the input stage (perhaps the output could be nested deeper depending on the function applied)

    – AAC
    Mar 28 at 21:24












  • If the lists are nested one level deep aways, why not [func(val) for val in list_of_lists] or event map(func, list_of_lists), it would simplify your function.

    – geckos
    Mar 28 at 21:30

















  • Will the lists only ever be nested one level deep?

    – Peter Collingridge
    Mar 28 at 21:08











  • @PeterCollingridge Yes, at least in the input stage (perhaps the output could be nested deeper depending on the function applied)

    – AAC
    Mar 28 at 21:24












  • If the lists are nested one level deep aways, why not [func(val) for val in list_of_lists] or event map(func, list_of_lists), it would simplify your function.

    – geckos
    Mar 28 at 21:30
















Will the lists only ever be nested one level deep?

– Peter Collingridge
Mar 28 at 21:08





Will the lists only ever be nested one level deep?

– Peter Collingridge
Mar 28 at 21:08













@PeterCollingridge Yes, at least in the input stage (perhaps the output could be nested deeper depending on the function applied)

– AAC
Mar 28 at 21:24






@PeterCollingridge Yes, at least in the input stage (perhaps the output could be nested deeper depending on the function applied)

– AAC
Mar 28 at 21:24














If the lists are nested one level deep aways, why not [func(val) for val in list_of_lists] or event map(func, list_of_lists), it would simplify your function.

– geckos
Mar 28 at 21:30





If the lists are nested one level deep aways, why not [func(val) for val in list_of_lists] or event map(func, list_of_lists), it would simplify your function.

– geckos
Mar 28 at 21:30












2 Answers
2






active

oldest

votes


















2
















How about:



def apply_f(a, b, f):
if isinstance(a, list):
return [apply_f(item_a, item_b, f) for item_a, item_b in zip(a, b)]
else:
return f(a, b)

result = apply_f(input1, input2, add)





share|improve this answer
































    0
















    Assuming the lists are always the right length (you can put a check for this), make your function recursive:



    def add(a, b):

    if isinstance(a, list) and isinstance(b, list):
    for a_sub, b_sub in zip(a, b):
    return [add(a_sub, b_sub) for a_sub, b_sub in zip(a, b)]

    elif "NULL" not in [a, b]:
    return a + b

    elif "NULL" in [a, b]:
    return "NULL"

    else:
    raise ValueError("Wrong input shapes")

    input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
    input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

    add(input1, input2)


    Output:



    [[10, 10, 'NULL'], [10, 10], [10, 10, 10, 10]]





    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/4.0/"u003ecc by-sa 4.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%2f55406703%2fhow-to-make-a-python-function-that-operates-on-two-or-more-nested-lists-of-the-s%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









      2
















      How about:



      def apply_f(a, b, f):
      if isinstance(a, list):
      return [apply_f(item_a, item_b, f) for item_a, item_b in zip(a, b)]
      else:
      return f(a, b)

      result = apply_f(input1, input2, add)





      share|improve this answer





























        2
















        How about:



        def apply_f(a, b, f):
        if isinstance(a, list):
        return [apply_f(item_a, item_b, f) for item_a, item_b in zip(a, b)]
        else:
        return f(a, b)

        result = apply_f(input1, input2, add)





        share|improve this answer



























          2














          2










          2









          How about:



          def apply_f(a, b, f):
          if isinstance(a, list):
          return [apply_f(item_a, item_b, f) for item_a, item_b in zip(a, b)]
          else:
          return f(a, b)

          result = apply_f(input1, input2, add)





          share|improve this answer













          How about:



          def apply_f(a, b, f):
          if isinstance(a, list):
          return [apply_f(item_a, item_b, f) for item_a, item_b in zip(a, b)]
          else:
          return f(a, b)

          result = apply_f(input1, input2, add)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 28 at 21:30









          Peter CollingridgePeter Collingridge

          8,5273 gold badges34 silver badges54 bronze badges




          8,5273 gold badges34 silver badges54 bronze badges


























              0
















              Assuming the lists are always the right length (you can put a check for this), make your function recursive:



              def add(a, b):

              if isinstance(a, list) and isinstance(b, list):
              for a_sub, b_sub in zip(a, b):
              return [add(a_sub, b_sub) for a_sub, b_sub in zip(a, b)]

              elif "NULL" not in [a, b]:
              return a + b

              elif "NULL" in [a, b]:
              return "NULL"

              else:
              raise ValueError("Wrong input shapes")

              input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
              input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

              add(input1, input2)


              Output:



              [[10, 10, 'NULL'], [10, 10], [10, 10, 10, 10]]





              share|improve this answer





























                0
















                Assuming the lists are always the right length (you can put a check for this), make your function recursive:



                def add(a, b):

                if isinstance(a, list) and isinstance(b, list):
                for a_sub, b_sub in zip(a, b):
                return [add(a_sub, b_sub) for a_sub, b_sub in zip(a, b)]

                elif "NULL" not in [a, b]:
                return a + b

                elif "NULL" in [a, b]:
                return "NULL"

                else:
                raise ValueError("Wrong input shapes")

                input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
                input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

                add(input1, input2)


                Output:



                [[10, 10, 'NULL'], [10, 10], [10, 10, 10, 10]]





                share|improve this answer



























                  0














                  0










                  0









                  Assuming the lists are always the right length (you can put a check for this), make your function recursive:



                  def add(a, b):

                  if isinstance(a, list) and isinstance(b, list):
                  for a_sub, b_sub in zip(a, b):
                  return [add(a_sub, b_sub) for a_sub, b_sub in zip(a, b)]

                  elif "NULL" not in [a, b]:
                  return a + b

                  elif "NULL" in [a, b]:
                  return "NULL"

                  else:
                  raise ValueError("Wrong input shapes")

                  input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
                  input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

                  add(input1, input2)


                  Output:



                  [[10, 10, 'NULL'], [10, 10], [10, 10, 10, 10]]





                  share|improve this answer













                  Assuming the lists are always the right length (you can put a check for this), make your function recursive:



                  def add(a, b):

                  if isinstance(a, list) and isinstance(b, list):
                  for a_sub, b_sub in zip(a, b):
                  return [add(a_sub, b_sub) for a_sub, b_sub in zip(a, b)]

                  elif "NULL" not in [a, b]:
                  return a + b

                  elif "NULL" in [a, b]:
                  return "NULL"

                  else:
                  raise ValueError("Wrong input shapes")

                  input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
                  input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

                  add(input1, input2)


                  Output:



                  [[10, 10, 'NULL'], [10, 10], [10, 10, 10, 10]]






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 21:29









                  dzangdzang

                  6093 silver badges10 bronze badges




                  6093 silver badges10 bronze badges































                      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%2f55406703%2fhow-to-make-a-python-function-that-operates-on-two-or-more-nested-lists-of-the-s%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

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript