Match list's index based off its value












1















I am new to Python and working on a problem where I have to match a list of indices to a list of value with 2 conditions:




  1. If there is a repeated index, then the values should be summed

  2. If there is no index in the list, then value should be 0


For example, below are my 2 lists: 'List of Inds' and 'List of Vals'. So at index 0, my value is 5; at index 1, my value is 4; at index 2, my value is 3 (2+1), at index 3, may value 0 (since no value associated with the index) and so on.



Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]


Output = [5,4,3,0,3]


I have been struggling with it for few days and can't find anything online that can point me in the right direction. Thank you.










share|improve this question

























  • How big are those lists? It's important to understand the physical size of the arrays in order to give a proper answer. One way to solve it would be to arrange the keys and values ahead of the calculation with appropriate data structures

    – orberkov
    Jan 19 at 16:17











  • Need to assume max length

    – Jane P
    Jan 19 at 16:20













  • what is the formula to calculate the output

    – Talha Israr
    Jan 19 at 16:21











  • Also is length of both lists equal

    – Talha Israr
    Jan 19 at 16:23






  • 1





    you need t o provide more information'

    – prashant rana
    Jan 19 at 16:33
















1















I am new to Python and working on a problem where I have to match a list of indices to a list of value with 2 conditions:




  1. If there is a repeated index, then the values should be summed

  2. If there is no index in the list, then value should be 0


For example, below are my 2 lists: 'List of Inds' and 'List of Vals'. So at index 0, my value is 5; at index 1, my value is 4; at index 2, my value is 3 (2+1), at index 3, may value 0 (since no value associated with the index) and so on.



Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]


Output = [5,4,3,0,3]


I have been struggling with it for few days and can't find anything online that can point me in the right direction. Thank you.










share|improve this question

























  • How big are those lists? It's important to understand the physical size of the arrays in order to give a proper answer. One way to solve it would be to arrange the keys and values ahead of the calculation with appropriate data structures

    – orberkov
    Jan 19 at 16:17











  • Need to assume max length

    – Jane P
    Jan 19 at 16:20













  • what is the formula to calculate the output

    – Talha Israr
    Jan 19 at 16:21











  • Also is length of both lists equal

    – Talha Israr
    Jan 19 at 16:23






  • 1





    you need t o provide more information'

    – prashant rana
    Jan 19 at 16:33














1












1








1








I am new to Python and working on a problem where I have to match a list of indices to a list of value with 2 conditions:




  1. If there is a repeated index, then the values should be summed

  2. If there is no index in the list, then value should be 0


For example, below are my 2 lists: 'List of Inds' and 'List of Vals'. So at index 0, my value is 5; at index 1, my value is 4; at index 2, my value is 3 (2+1), at index 3, may value 0 (since no value associated with the index) and so on.



Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]


Output = [5,4,3,0,3]


I have been struggling with it for few days and can't find anything online that can point me in the right direction. Thank you.










share|improve this question
















I am new to Python and working on a problem where I have to match a list of indices to a list of value with 2 conditions:




  1. If there is a repeated index, then the values should be summed

  2. If there is no index in the list, then value should be 0


For example, below are my 2 lists: 'List of Inds' and 'List of Vals'. So at index 0, my value is 5; at index 1, my value is 4; at index 2, my value is 3 (2+1), at index 3, may value 0 (since no value associated with the index) and so on.



Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]


Output = [5,4,3,0,3]


I have been struggling with it for few days and can't find anything online that can point me in the right direction. Thank you.







python list dictionary indexing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 19 at 16:34









ggorlen

7,1883825




7,1883825










asked Jan 19 at 16:07









Jane PJane P

373




373













  • How big are those lists? It's important to understand the physical size of the arrays in order to give a proper answer. One way to solve it would be to arrange the keys and values ahead of the calculation with appropriate data structures

    – orberkov
    Jan 19 at 16:17











  • Need to assume max length

    – Jane P
    Jan 19 at 16:20













  • what is the formula to calculate the output

    – Talha Israr
    Jan 19 at 16:21











  • Also is length of both lists equal

    – Talha Israr
    Jan 19 at 16:23






  • 1





    you need t o provide more information'

    – prashant rana
    Jan 19 at 16:33



















  • How big are those lists? It's important to understand the physical size of the arrays in order to give a proper answer. One way to solve it would be to arrange the keys and values ahead of the calculation with appropriate data structures

    – orberkov
    Jan 19 at 16:17











  • Need to assume max length

    – Jane P
    Jan 19 at 16:20













  • what is the formula to calculate the output

    – Talha Israr
    Jan 19 at 16:21











  • Also is length of both lists equal

    – Talha Israr
    Jan 19 at 16:23






  • 1





    you need t o provide more information'

    – prashant rana
    Jan 19 at 16:33

















How big are those lists? It's important to understand the physical size of the arrays in order to give a proper answer. One way to solve it would be to arrange the keys and values ahead of the calculation with appropriate data structures

– orberkov
Jan 19 at 16:17





How big are those lists? It's important to understand the physical size of the arrays in order to give a proper answer. One way to solve it would be to arrange the keys and values ahead of the calculation with appropriate data structures

– orberkov
Jan 19 at 16:17













Need to assume max length

– Jane P
Jan 19 at 16:20







Need to assume max length

– Jane P
Jan 19 at 16:20















what is the formula to calculate the output

– Talha Israr
Jan 19 at 16:21





what is the formula to calculate the output

– Talha Israr
Jan 19 at 16:21













Also is length of both lists equal

– Talha Israr
Jan 19 at 16:23





Also is length of both lists equal

– Talha Israr
Jan 19 at 16:23




1




1





you need t o provide more information'

– prashant rana
Jan 19 at 16:33





you need t o provide more information'

– prashant rana
Jan 19 at 16:33












5 Answers
5






active

oldest

votes


















0














List_of_Inds = [0,1,4,2,2]
List_Vals = [5,4,3,2,1]
dic ={}

i = 0
for key in List_of_Inds:
if key not in dic:
dic[key] = 0
dic[key] = List_Vals[i]+dic[key]
i = i+1

output =
for key in range(0, len(dic)+1):
if key in dic:
output.append(dic[key])
else:
output.append(0)

print(dic)
print(output)


output:



{0: 5, 1: 4, 4: 3, 2: 3}
[5, 4, 3, 0, 3]





share|improve this answer































    0














    The following code works as desired. In computer science it is called "Sparse Matrix" where the data is kept only for said indices, but the "virtual size" of the data structure seems large from the outside.



    import logging

    class SparseVector:
    def __init__(self, indices, values):
    self.d = {}
    for c, indx in enumerate(indices):
    logging.info(c)
    logging.info(indx)
    if indx not in self.d:
    self.d[indx] = 0
    self.d[indx] += values[c]

    def getItem(self, key):
    if key in self.d:
    return self.d[key]
    else:
    return 0

    p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
    print p1.getItem(0);
    print p1.getItem(1);
    print p1.getItem(2);
    print p1.getItem(3);
    print p1.getItem(4);
    print p1.getItem(5);
    print p1.getItem(6);





    share|improve this answer































      0














      Answer code is



      def ans(list1,list2):
      dic={}
      ans=
      if not(len(list1)==len(list2)):
      return "Not Possible"
      for i in range(0,len(list1)):
      ind=list1[i]
      val=list2[i]
      if not(ind in dic.keys()):
      dic[ind]=val
      else:
      dic[ind]+=val
      val=len(list1)
      for i in range(0,val):
      if not(i in dic.keys()):
      ans.append(0)
      else:
      ans.append(dic[i])
      return ans


      To test:



        print(ans([0,1,4,2,2], [5,4,3,2,1]))


      output:



        [5, 4, 3, 0, 3]


      Hope it helps



      Comment if you dont understand any step






      share|improve this answer































        0














        what you can do is sort the indexes and values in an ascending order, and then sum it up. Here is an example code:



        import numpy as np

        ind = [0,1,4,2,2]
        vals = [5,4,3,2,1]

        points = zip(ind,vals)

        sorted_points = sorted(points)

        new_ind = [point[0] for point in sorted_points]
        new_val = [point[1] for point in sorted_points]

        output = np.zeros((len(new_ind)))

        for i in range(len(new_ind)):
        output[new_ind[i]] += new_val[i]


        In this code, the index values are sorted to be in ascending order and then the value array is rearranged according to the sorted index array. Then, using a simple for loop, you can sum the values of each existing index and calculate the output.






        share|improve this answer































          0














          This is a grouping problem. You can use collections.defaultdict to build a dictionary mapping, incrementing values in each iteration. Then use a list comprehension:



          indices = [0,1,4,2,2]
          values = [5,4,3,2,1]

          from collections import defaultdict
          dd = defaultdict(int)
          for idx, val in zip(indices, values):
          dd[idx] += val

          res = [dd[idx] for idx in range(max(dd) + 1)]

          ## functional alternative:
          # res = list(map(dd.get, range(max(dd) + 1)))

          print(res)
          # [5, 4, 3, 0, 3]





          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%2f54268922%2fmatch-lists-index-based-off-its-value%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            List_of_Inds = [0,1,4,2,2]
            List_Vals = [5,4,3,2,1]
            dic ={}

            i = 0
            for key in List_of_Inds:
            if key not in dic:
            dic[key] = 0
            dic[key] = List_Vals[i]+dic[key]
            i = i+1

            output =
            for key in range(0, len(dic)+1):
            if key in dic:
            output.append(dic[key])
            else:
            output.append(0)

            print(dic)
            print(output)


            output:



            {0: 5, 1: 4, 4: 3, 2: 3}
            [5, 4, 3, 0, 3]





            share|improve this answer




























              0














              List_of_Inds = [0,1,4,2,2]
              List_Vals = [5,4,3,2,1]
              dic ={}

              i = 0
              for key in List_of_Inds:
              if key not in dic:
              dic[key] = 0
              dic[key] = List_Vals[i]+dic[key]
              i = i+1

              output =
              for key in range(0, len(dic)+1):
              if key in dic:
              output.append(dic[key])
              else:
              output.append(0)

              print(dic)
              print(output)


              output:



              {0: 5, 1: 4, 4: 3, 2: 3}
              [5, 4, 3, 0, 3]





              share|improve this answer


























                0












                0








                0







                List_of_Inds = [0,1,4,2,2]
                List_Vals = [5,4,3,2,1]
                dic ={}

                i = 0
                for key in List_of_Inds:
                if key not in dic:
                dic[key] = 0
                dic[key] = List_Vals[i]+dic[key]
                i = i+1

                output =
                for key in range(0, len(dic)+1):
                if key in dic:
                output.append(dic[key])
                else:
                output.append(0)

                print(dic)
                print(output)


                output:



                {0: 5, 1: 4, 4: 3, 2: 3}
                [5, 4, 3, 0, 3]





                share|improve this answer













                List_of_Inds = [0,1,4,2,2]
                List_Vals = [5,4,3,2,1]
                dic ={}

                i = 0
                for key in List_of_Inds:
                if key not in dic:
                dic[key] = 0
                dic[key] = List_Vals[i]+dic[key]
                i = i+1

                output =
                for key in range(0, len(dic)+1):
                if key in dic:
                output.append(dic[key])
                else:
                output.append(0)

                print(dic)
                print(output)


                output:



                {0: 5, 1: 4, 4: 3, 2: 3}
                [5, 4, 3, 0, 3]






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 19 at 17:23









                ponylamaponylama

                362




                362

























                    0














                    The following code works as desired. In computer science it is called "Sparse Matrix" where the data is kept only for said indices, but the "virtual size" of the data structure seems large from the outside.



                    import logging

                    class SparseVector:
                    def __init__(self, indices, values):
                    self.d = {}
                    for c, indx in enumerate(indices):
                    logging.info(c)
                    logging.info(indx)
                    if indx not in self.d:
                    self.d[indx] = 0
                    self.d[indx] += values[c]

                    def getItem(self, key):
                    if key in self.d:
                    return self.d[key]
                    else:
                    return 0

                    p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
                    print p1.getItem(0);
                    print p1.getItem(1);
                    print p1.getItem(2);
                    print p1.getItem(3);
                    print p1.getItem(4);
                    print p1.getItem(5);
                    print p1.getItem(6);





                    share|improve this answer




























                      0














                      The following code works as desired. In computer science it is called "Sparse Matrix" where the data is kept only for said indices, but the "virtual size" of the data structure seems large from the outside.



                      import logging

                      class SparseVector:
                      def __init__(self, indices, values):
                      self.d = {}
                      for c, indx in enumerate(indices):
                      logging.info(c)
                      logging.info(indx)
                      if indx not in self.d:
                      self.d[indx] = 0
                      self.d[indx] += values[c]

                      def getItem(self, key):
                      if key in self.d:
                      return self.d[key]
                      else:
                      return 0

                      p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
                      print p1.getItem(0);
                      print p1.getItem(1);
                      print p1.getItem(2);
                      print p1.getItem(3);
                      print p1.getItem(4);
                      print p1.getItem(5);
                      print p1.getItem(6);





                      share|improve this answer


























                        0












                        0








                        0







                        The following code works as desired. In computer science it is called "Sparse Matrix" where the data is kept only for said indices, but the "virtual size" of the data structure seems large from the outside.



                        import logging

                        class SparseVector:
                        def __init__(self, indices, values):
                        self.d = {}
                        for c, indx in enumerate(indices):
                        logging.info(c)
                        logging.info(indx)
                        if indx not in self.d:
                        self.d[indx] = 0
                        self.d[indx] += values[c]

                        def getItem(self, key):
                        if key in self.d:
                        return self.d[key]
                        else:
                        return 0

                        p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
                        print p1.getItem(0);
                        print p1.getItem(1);
                        print p1.getItem(2);
                        print p1.getItem(3);
                        print p1.getItem(4);
                        print p1.getItem(5);
                        print p1.getItem(6);





                        share|improve this answer













                        The following code works as desired. In computer science it is called "Sparse Matrix" where the data is kept only for said indices, but the "virtual size" of the data structure seems large from the outside.



                        import logging

                        class SparseVector:
                        def __init__(self, indices, values):
                        self.d = {}
                        for c, indx in enumerate(indices):
                        logging.info(c)
                        logging.info(indx)
                        if indx not in self.d:
                        self.d[indx] = 0
                        self.d[indx] += values[c]

                        def getItem(self, key):
                        if key in self.d:
                        return self.d[key]
                        else:
                        return 0

                        p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
                        print p1.getItem(0);
                        print p1.getItem(1);
                        print p1.getItem(2);
                        print p1.getItem(3);
                        print p1.getItem(4);
                        print p1.getItem(5);
                        print p1.getItem(6);






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 19 at 16:48









                        orberkovorberkov

                        3411416




                        3411416























                            0














                            Answer code is



                            def ans(list1,list2):
                            dic={}
                            ans=
                            if not(len(list1)==len(list2)):
                            return "Not Possible"
                            for i in range(0,len(list1)):
                            ind=list1[i]
                            val=list2[i]
                            if not(ind in dic.keys()):
                            dic[ind]=val
                            else:
                            dic[ind]+=val
                            val=len(list1)
                            for i in range(0,val):
                            if not(i in dic.keys()):
                            ans.append(0)
                            else:
                            ans.append(dic[i])
                            return ans


                            To test:



                              print(ans([0,1,4,2,2], [5,4,3,2,1]))


                            output:



                              [5, 4, 3, 0, 3]


                            Hope it helps



                            Comment if you dont understand any step






                            share|improve this answer




























                              0














                              Answer code is



                              def ans(list1,list2):
                              dic={}
                              ans=
                              if not(len(list1)==len(list2)):
                              return "Not Possible"
                              for i in range(0,len(list1)):
                              ind=list1[i]
                              val=list2[i]
                              if not(ind in dic.keys()):
                              dic[ind]=val
                              else:
                              dic[ind]+=val
                              val=len(list1)
                              for i in range(0,val):
                              if not(i in dic.keys()):
                              ans.append(0)
                              else:
                              ans.append(dic[i])
                              return ans


                              To test:



                                print(ans([0,1,4,2,2], [5,4,3,2,1]))


                              output:



                                [5, 4, 3, 0, 3]


                              Hope it helps



                              Comment if you dont understand any step






                              share|improve this answer


























                                0












                                0








                                0







                                Answer code is



                                def ans(list1,list2):
                                dic={}
                                ans=
                                if not(len(list1)==len(list2)):
                                return "Not Possible"
                                for i in range(0,len(list1)):
                                ind=list1[i]
                                val=list2[i]
                                if not(ind in dic.keys()):
                                dic[ind]=val
                                else:
                                dic[ind]+=val
                                val=len(list1)
                                for i in range(0,val):
                                if not(i in dic.keys()):
                                ans.append(0)
                                else:
                                ans.append(dic[i])
                                return ans


                                To test:



                                  print(ans([0,1,4,2,2], [5,4,3,2,1]))


                                output:



                                  [5, 4, 3, 0, 3]


                                Hope it helps



                                Comment if you dont understand any step






                                share|improve this answer













                                Answer code is



                                def ans(list1,list2):
                                dic={}
                                ans=
                                if not(len(list1)==len(list2)):
                                return "Not Possible"
                                for i in range(0,len(list1)):
                                ind=list1[i]
                                val=list2[i]
                                if not(ind in dic.keys()):
                                dic[ind]=val
                                else:
                                dic[ind]+=val
                                val=len(list1)
                                for i in range(0,val):
                                if not(i in dic.keys()):
                                ans.append(0)
                                else:
                                ans.append(dic[i])
                                return ans


                                To test:



                                  print(ans([0,1,4,2,2], [5,4,3,2,1]))


                                output:



                                  [5, 4, 3, 0, 3]


                                Hope it helps



                                Comment if you dont understand any step







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 19 at 16:49









                                Talha IsrarTalha Israr

                                472212




                                472212























                                    0














                                    what you can do is sort the indexes and values in an ascending order, and then sum it up. Here is an example code:



                                    import numpy as np

                                    ind = [0,1,4,2,2]
                                    vals = [5,4,3,2,1]

                                    points = zip(ind,vals)

                                    sorted_points = sorted(points)

                                    new_ind = [point[0] for point in sorted_points]
                                    new_val = [point[1] for point in sorted_points]

                                    output = np.zeros((len(new_ind)))

                                    for i in range(len(new_ind)):
                                    output[new_ind[i]] += new_val[i]


                                    In this code, the index values are sorted to be in ascending order and then the value array is rearranged according to the sorted index array. Then, using a simple for loop, you can sum the values of each existing index and calculate the output.






                                    share|improve this answer




























                                      0














                                      what you can do is sort the indexes and values in an ascending order, and then sum it up. Here is an example code:



                                      import numpy as np

                                      ind = [0,1,4,2,2]
                                      vals = [5,4,3,2,1]

                                      points = zip(ind,vals)

                                      sorted_points = sorted(points)

                                      new_ind = [point[0] for point in sorted_points]
                                      new_val = [point[1] for point in sorted_points]

                                      output = np.zeros((len(new_ind)))

                                      for i in range(len(new_ind)):
                                      output[new_ind[i]] += new_val[i]


                                      In this code, the index values are sorted to be in ascending order and then the value array is rearranged according to the sorted index array. Then, using a simple for loop, you can sum the values of each existing index and calculate the output.






                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        what you can do is sort the indexes and values in an ascending order, and then sum it up. Here is an example code:



                                        import numpy as np

                                        ind = [0,1,4,2,2]
                                        vals = [5,4,3,2,1]

                                        points = zip(ind,vals)

                                        sorted_points = sorted(points)

                                        new_ind = [point[0] for point in sorted_points]
                                        new_val = [point[1] for point in sorted_points]

                                        output = np.zeros((len(new_ind)))

                                        for i in range(len(new_ind)):
                                        output[new_ind[i]] += new_val[i]


                                        In this code, the index values are sorted to be in ascending order and then the value array is rearranged according to the sorted index array. Then, using a simple for loop, you can sum the values of each existing index and calculate the output.






                                        share|improve this answer













                                        what you can do is sort the indexes and values in an ascending order, and then sum it up. Here is an example code:



                                        import numpy as np

                                        ind = [0,1,4,2,2]
                                        vals = [5,4,3,2,1]

                                        points = zip(ind,vals)

                                        sorted_points = sorted(points)

                                        new_ind = [point[0] for point in sorted_points]
                                        new_val = [point[1] for point in sorted_points]

                                        output = np.zeros((len(new_ind)))

                                        for i in range(len(new_ind)):
                                        output[new_ind[i]] += new_val[i]


                                        In this code, the index values are sorted to be in ascending order and then the value array is rearranged according to the sorted index array. Then, using a simple for loop, you can sum the values of each existing index and calculate the output.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jan 19 at 16:53









                                        Koralp CatalsakalKoralp Catalsakal

                                        33215




                                        33215























                                            0














                                            This is a grouping problem. You can use collections.defaultdict to build a dictionary mapping, incrementing values in each iteration. Then use a list comprehension:



                                            indices = [0,1,4,2,2]
                                            values = [5,4,3,2,1]

                                            from collections import defaultdict
                                            dd = defaultdict(int)
                                            for idx, val in zip(indices, values):
                                            dd[idx] += val

                                            res = [dd[idx] for idx in range(max(dd) + 1)]

                                            ## functional alternative:
                                            # res = list(map(dd.get, range(max(dd) + 1)))

                                            print(res)
                                            # [5, 4, 3, 0, 3]





                                            share|improve this answer




























                                              0














                                              This is a grouping problem. You can use collections.defaultdict to build a dictionary mapping, incrementing values in each iteration. Then use a list comprehension:



                                              indices = [0,1,4,2,2]
                                              values = [5,4,3,2,1]

                                              from collections import defaultdict
                                              dd = defaultdict(int)
                                              for idx, val in zip(indices, values):
                                              dd[idx] += val

                                              res = [dd[idx] for idx in range(max(dd) + 1)]

                                              ## functional alternative:
                                              # res = list(map(dd.get, range(max(dd) + 1)))

                                              print(res)
                                              # [5, 4, 3, 0, 3]





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                This is a grouping problem. You can use collections.defaultdict to build a dictionary mapping, incrementing values in each iteration. Then use a list comprehension:



                                                indices = [0,1,4,2,2]
                                                values = [5,4,3,2,1]

                                                from collections import defaultdict
                                                dd = defaultdict(int)
                                                for idx, val in zip(indices, values):
                                                dd[idx] += val

                                                res = [dd[idx] for idx in range(max(dd) + 1)]

                                                ## functional alternative:
                                                # res = list(map(dd.get, range(max(dd) + 1)))

                                                print(res)
                                                # [5, 4, 3, 0, 3]





                                                share|improve this answer













                                                This is a grouping problem. You can use collections.defaultdict to build a dictionary mapping, incrementing values in each iteration. Then use a list comprehension:



                                                indices = [0,1,4,2,2]
                                                values = [5,4,3,2,1]

                                                from collections import defaultdict
                                                dd = defaultdict(int)
                                                for idx, val in zip(indices, values):
                                                dd[idx] += val

                                                res = [dd[idx] for idx in range(max(dd) + 1)]

                                                ## functional alternative:
                                                # res = list(map(dd.get, range(max(dd) + 1)))

                                                print(res)
                                                # [5, 4, 3, 0, 3]






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jan 19 at 17:51









                                                jppjpp

                                                99.5k2161110




                                                99.5k2161110






























                                                    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%2f54268922%2fmatch-lists-index-based-off-its-value%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

                                                    Liquibase includeAll doesn't find base path

                                                    How to use setInterval in EJS file?

                                                    Petrus Granier-Deferre