【问题标题】:Match list's index based off its value匹配列表的索引基于其值
【发布时间】:2019-01-19 16:07:14
【问题描述】:

我是 Python 新手,正在解决一个问题,我必须将索引列表与具有 2 个条件的值列表进行匹配:

  1. 如果存在重复索引,则应将值相加
  2. 如果列表中没有索引,则值应为 0

例如,下面是我的 2 个列表:“Inds 列表”和“Vals 列表”。所以在索引 0 处,我的值为 5;在索引 1 处,我的值为 4;在索引 2 处,我的值为 3 (2+1),在索引 3 处,可能值为 0(因为没有与索引关联的值)等等。

Input:

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

我已经为此苦苦挣扎了几天,在网上找不到任何可以为我指明正确方向的东西。谢谢。

【问题讨论】:

  • 这些列表有多大?为了给出正确的答案,了解阵列的物理大小很重要。解决它的一种方法是在计算之前使用适当的数据结构安排键和值
  • 需要假设最大长度
  • 计算输出的公式是什么
  • 两个列表的长度也相等
  • 您需要提供更多信息'

标签: python list dictionary indexing


【解决方案1】:
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)

输出:

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

【讨论】:

    【解决方案2】:

    以下代码可以按需要工作。在计算机科学中,它被称为“稀疏矩阵”,其中数据仅针对所述索引保留,但数据结构的“虚拟大小”从外部看起来很大。

    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);
    

    【讨论】:

      【解决方案3】:

      答案代码是

      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
      

      测试:

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

      输出:

        [5, 4, 3, 0, 3]
      

      希望对你有帮助

      如果有不明白的步骤请留言

      【讨论】:

        【解决方案4】:

        你可以做的是将索引和值按升序排序,然后求和。这是一个示例代码:

        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]    
        

        在此代码中,索引值按升序排序,然后根据排序后的索引数组重新排列值数组。然后,使用简单的 for 循环,您可以对每个现有索引的值求和并计算输出。

        【讨论】:

          【解决方案5】:

          这是一个分组问题。您可以使用collections.defaultdict 构建字典映射,在每次迭代中递增值。然后使用列表推导:

          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]
          

          【讨论】:

            猜你喜欢
            • 2020-08-30
            • 2019-02-17
            • 1970-01-01
            • 2015-02-12
            • 1970-01-01
            • 1970-01-01
            • 2023-04-01
            • 2021-01-07
            • 1970-01-01
            相关资源
            最近更新 更多