How to locate the index with in a nested list Python











up vote
0
down vote

favorite












from typing import List



def find_peak(m: List[List[int]]) -> List[int]:
"""
Given an non-empty elevation map m, returns the cell of the
highest point in m.

Examples (note some spacing has been added for human readablity)
>>> m = [[1,2,3],
[9,8,7],
[5,4,6]]
>>> find_peak(m)
[1,0]
>>> m = [[6,2,3],
[1,8,7],
[5,4,9]]
>>> find_peak(m)
[2,2]
"""
max_location =
for sublist in m:
max_location.append(max(sublist))
max_location = max(max_location)
for sublist in m:
if max_location in sublist:
return (m.index(max_location),sublist.index(max_location))


this doesnt really work since it just returns that number is not in list










share|improve this question




























    up vote
    0
    down vote

    favorite












    from typing import List



    def find_peak(m: List[List[int]]) -> List[int]:
    """
    Given an non-empty elevation map m, returns the cell of the
    highest point in m.

    Examples (note some spacing has been added for human readablity)
    >>> m = [[1,2,3],
    [9,8,7],
    [5,4,6]]
    >>> find_peak(m)
    [1,0]
    >>> m = [[6,2,3],
    [1,8,7],
    [5,4,9]]
    >>> find_peak(m)
    [2,2]
    """
    max_location =
    for sublist in m:
    max_location.append(max(sublist))
    max_location = max(max_location)
    for sublist in m:
    if max_location in sublist:
    return (m.index(max_location),sublist.index(max_location))


    this doesnt really work since it just returns that number is not in list










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      from typing import List



      def find_peak(m: List[List[int]]) -> List[int]:
      """
      Given an non-empty elevation map m, returns the cell of the
      highest point in m.

      Examples (note some spacing has been added for human readablity)
      >>> m = [[1,2,3],
      [9,8,7],
      [5,4,6]]
      >>> find_peak(m)
      [1,0]
      >>> m = [[6,2,3],
      [1,8,7],
      [5,4,9]]
      >>> find_peak(m)
      [2,2]
      """
      max_location =
      for sublist in m:
      max_location.append(max(sublist))
      max_location = max(max_location)
      for sublist in m:
      if max_location in sublist:
      return (m.index(max_location),sublist.index(max_location))


      this doesnt really work since it just returns that number is not in list










      share|improve this question















      from typing import List



      def find_peak(m: List[List[int]]) -> List[int]:
      """
      Given an non-empty elevation map m, returns the cell of the
      highest point in m.

      Examples (note some spacing has been added for human readablity)
      >>> m = [[1,2,3],
      [9,8,7],
      [5,4,6]]
      >>> find_peak(m)
      [1,0]
      >>> m = [[6,2,3],
      [1,8,7],
      [5,4,9]]
      >>> find_peak(m)
      [2,2]
      """
      max_location =
      for sublist in m:
      max_location.append(max(sublist))
      max_location = max(max_location)
      for sublist in m:
      if max_location in sublist:
      return (m.index(max_location),sublist.index(max_location))


      this doesnt really work since it just returns that number is not in list







      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 at 4:51









      sacul

      29.1k41639




      29.1k41639










      asked Nov 9 at 4:50









      Beier Mu

      2




      2
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          1
          down vote













          You can also make good use of enumerate. First find the row (with its index) with the maximum number. Then find that number and its index in that row.



          In both cases you need to provide a key to the max function so that it considers the value (not the index):



          def find_peak(m):
          i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
          j, max_val = max(enumerate(max_row), key=lambda x: x[1])
          return [i, j]


          Output



          print(find_peak([[1,2,3], [9,8,7], [5,4,6]]))
          # [1, 0]
          print(find_peak([[6,2,3], [1,8,7], [5,4,9]]))
          # [2, 2]





          share|improve this answer






























            up vote
            0
            down vote













            You can find the maximum value in the flattened input structure, and then return the coordinates that specify the location of the maximum value previously found:



            from typing import List
            def find_peak(m: List[List[int]]) -> List[int]:
            _max = max([i for b in m for i in b])
            return [[i, a] for i in range(len(m)) for a in range(len(m[0])) if m[i][a] == _max][0]

            print(list(map(find_peak, [[[1, 2, 3], [9, 8, 7], [5, 4, 6]], [[6, 2, 3], [1, 8, 7], [5, 4, 9]]])))


            Output:



            [[1, 0], [2, 2]]





            share|improve this answer





















            • @BeierMu Glad to help! If this answer assisted you, please accept it.
              – Ajax1234
              Nov 9 at 5:05


















            up vote
            0
            down vote













            I think its easier when you think about iterating over indices rather than the items on the list:



            from itertools import product

            d = [[1, 2, 3], [7, 9, 8], [4, 5, 6]]

            # generate all indices
            x_len = range(len(d))
            y_len = range(len(d[0]))
            indices = product(x_len, y_len)

            # select maximal item by index
            key = lambda x: d[x[0]][x[1]]
            max_index = max(indices, key=key)

            print(max_index)





            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',
              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%2f53220035%2fhow-to-locate-the-index-with-in-a-nested-list-python%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              1
              down vote













              You can also make good use of enumerate. First find the row (with its index) with the maximum number. Then find that number and its index in that row.



              In both cases you need to provide a key to the max function so that it considers the value (not the index):



              def find_peak(m):
              i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
              j, max_val = max(enumerate(max_row), key=lambda x: x[1])
              return [i, j]


              Output



              print(find_peak([[1,2,3], [9,8,7], [5,4,6]]))
              # [1, 0]
              print(find_peak([[6,2,3], [1,8,7], [5,4,9]]))
              # [2, 2]





              share|improve this answer



























                up vote
                1
                down vote













                You can also make good use of enumerate. First find the row (with its index) with the maximum number. Then find that number and its index in that row.



                In both cases you need to provide a key to the max function so that it considers the value (not the index):



                def find_peak(m):
                i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
                j, max_val = max(enumerate(max_row), key=lambda x: x[1])
                return [i, j]


                Output



                print(find_peak([[1,2,3], [9,8,7], [5,4,6]]))
                # [1, 0]
                print(find_peak([[6,2,3], [1,8,7], [5,4,9]]))
                # [2, 2]





                share|improve this answer

























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  You can also make good use of enumerate. First find the row (with its index) with the maximum number. Then find that number and its index in that row.



                  In both cases you need to provide a key to the max function so that it considers the value (not the index):



                  def find_peak(m):
                  i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
                  j, max_val = max(enumerate(max_row), key=lambda x: x[1])
                  return [i, j]


                  Output



                  print(find_peak([[1,2,3], [9,8,7], [5,4,6]]))
                  # [1, 0]
                  print(find_peak([[6,2,3], [1,8,7], [5,4,9]]))
                  # [2, 2]





                  share|improve this answer














                  You can also make good use of enumerate. First find the row (with its index) with the maximum number. Then find that number and its index in that row.



                  In both cases you need to provide a key to the max function so that it considers the value (not the index):



                  def find_peak(m):
                  i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
                  j, max_val = max(enumerate(max_row), key=lambda x: x[1])
                  return [i, j]


                  Output



                  print(find_peak([[1,2,3], [9,8,7], [5,4,6]]))
                  # [1, 0]
                  print(find_peak([[6,2,3], [1,8,7], [5,4,9]]))
                  # [2, 2]






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 9 at 5:10

























                  answered Nov 9 at 5:00









                  slider

                  7,7551129




                  7,7551129
























                      up vote
                      0
                      down vote













                      You can find the maximum value in the flattened input structure, and then return the coordinates that specify the location of the maximum value previously found:



                      from typing import List
                      def find_peak(m: List[List[int]]) -> List[int]:
                      _max = max([i for b in m for i in b])
                      return [[i, a] for i in range(len(m)) for a in range(len(m[0])) if m[i][a] == _max][0]

                      print(list(map(find_peak, [[[1, 2, 3], [9, 8, 7], [5, 4, 6]], [[6, 2, 3], [1, 8, 7], [5, 4, 9]]])))


                      Output:



                      [[1, 0], [2, 2]]





                      share|improve this answer





















                      • @BeierMu Glad to help! If this answer assisted you, please accept it.
                        – Ajax1234
                        Nov 9 at 5:05















                      up vote
                      0
                      down vote













                      You can find the maximum value in the flattened input structure, and then return the coordinates that specify the location of the maximum value previously found:



                      from typing import List
                      def find_peak(m: List[List[int]]) -> List[int]:
                      _max = max([i for b in m for i in b])
                      return [[i, a] for i in range(len(m)) for a in range(len(m[0])) if m[i][a] == _max][0]

                      print(list(map(find_peak, [[[1, 2, 3], [9, 8, 7], [5, 4, 6]], [[6, 2, 3], [1, 8, 7], [5, 4, 9]]])))


                      Output:



                      [[1, 0], [2, 2]]





                      share|improve this answer





















                      • @BeierMu Glad to help! If this answer assisted you, please accept it.
                        – Ajax1234
                        Nov 9 at 5:05













                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      You can find the maximum value in the flattened input structure, and then return the coordinates that specify the location of the maximum value previously found:



                      from typing import List
                      def find_peak(m: List[List[int]]) -> List[int]:
                      _max = max([i for b in m for i in b])
                      return [[i, a] for i in range(len(m)) for a in range(len(m[0])) if m[i][a] == _max][0]

                      print(list(map(find_peak, [[[1, 2, 3], [9, 8, 7], [5, 4, 6]], [[6, 2, 3], [1, 8, 7], [5, 4, 9]]])))


                      Output:



                      [[1, 0], [2, 2]]





                      share|improve this answer












                      You can find the maximum value in the flattened input structure, and then return the coordinates that specify the location of the maximum value previously found:



                      from typing import List
                      def find_peak(m: List[List[int]]) -> List[int]:
                      _max = max([i for b in m for i in b])
                      return [[i, a] for i in range(len(m)) for a in range(len(m[0])) if m[i][a] == _max][0]

                      print(list(map(find_peak, [[[1, 2, 3], [9, 8, 7], [5, 4, 6]], [[6, 2, 3], [1, 8, 7], [5, 4, 9]]])))


                      Output:



                      [[1, 0], [2, 2]]






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 9 at 4:59









                      Ajax1234

                      39.3k42552




                      39.3k42552












                      • @BeierMu Glad to help! If this answer assisted you, please accept it.
                        – Ajax1234
                        Nov 9 at 5:05


















                      • @BeierMu Glad to help! If this answer assisted you, please accept it.
                        – Ajax1234
                        Nov 9 at 5:05
















                      @BeierMu Glad to help! If this answer assisted you, please accept it.
                      – Ajax1234
                      Nov 9 at 5:05




                      @BeierMu Glad to help! If this answer assisted you, please accept it.
                      – Ajax1234
                      Nov 9 at 5:05










                      up vote
                      0
                      down vote













                      I think its easier when you think about iterating over indices rather than the items on the list:



                      from itertools import product

                      d = [[1, 2, 3], [7, 9, 8], [4, 5, 6]]

                      # generate all indices
                      x_len = range(len(d))
                      y_len = range(len(d[0]))
                      indices = product(x_len, y_len)

                      # select maximal item by index
                      key = lambda x: d[x[0]][x[1]]
                      max_index = max(indices, key=key)

                      print(max_index)





                      share|improve this answer

























                        up vote
                        0
                        down vote













                        I think its easier when you think about iterating over indices rather than the items on the list:



                        from itertools import product

                        d = [[1, 2, 3], [7, 9, 8], [4, 5, 6]]

                        # generate all indices
                        x_len = range(len(d))
                        y_len = range(len(d[0]))
                        indices = product(x_len, y_len)

                        # select maximal item by index
                        key = lambda x: d[x[0]][x[1]]
                        max_index = max(indices, key=key)

                        print(max_index)





                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          I think its easier when you think about iterating over indices rather than the items on the list:



                          from itertools import product

                          d = [[1, 2, 3], [7, 9, 8], [4, 5, 6]]

                          # generate all indices
                          x_len = range(len(d))
                          y_len = range(len(d[0]))
                          indices = product(x_len, y_len)

                          # select maximal item by index
                          key = lambda x: d[x[0]][x[1]]
                          max_index = max(indices, key=key)

                          print(max_index)





                          share|improve this answer












                          I think its easier when you think about iterating over indices rather than the items on the list:



                          from itertools import product

                          d = [[1, 2, 3], [7, 9, 8], [4, 5, 6]]

                          # generate all indices
                          x_len = range(len(d))
                          y_len = range(len(d[0]))
                          indices = product(x_len, y_len)

                          # select maximal item by index
                          key = lambda x: d[x[0]][x[1]]
                          max_index = max(indices, key=key)

                          print(max_index)






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 9 at 5:21









                          Reut Sharabani

                          22.7k44664




                          22.7k44664






























                              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%2f53220035%2fhow-to-locate-the-index-with-in-a-nested-list-python%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







                              這個網誌中的熱門文章

                              Tangent Lines Diagram Along Smooth Curve

                              Yusuf al-Mu'taman ibn Hud

                              Zucchini