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

                      How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                      Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?