【问题标题】:Add items from a list based on a second list in python根据python中的第二个列表从列表中添加项目
【发布时间】:2018-12-01 10:25:08
【问题描述】:

我有两个列表。我想根据列表颜色在 vp 中添加值。 所以我想要这个输出:

total = [60,90,60]

因为我希望代码运行如下:total = [10+20+30, 40+50,60]

total = []
vp = [10,20,30,40,50,60]
color = [3,2,1]

我不知道该怎么做。我在 python3 中开始了这样的事情:

for c, v in zip(color, Vp):
    total.append ....

谢谢你

【问题讨论】:

    标签: python list loops


    【解决方案1】:

    您可以对列表进行一些切片,以根据另一个列表中的内容从原始列表中收集元素,将其汇总并附加到最​​终列表:

    total = []
    vp = [10,20,30,40,50,60]
    color = [3,2,1]
    
    i = 0
    for x in color:
        total.append(sum(vp[i:i+x]))
        i += x
    
    print(total)
    # [60, 90, 60]
    

    【讨论】:

      【解决方案2】:

      这个答案对于这个例子来说并不理想,但是当你想将密集表示转换为稀疏表示时,它可能对其他情况很有用。在这种情况下,我们将一维数组转换为带有填充的二维数组。例如,您希望能够使用np.sum

      total = []
      vp = [10,20,30,40,50,60]
      color = [3,2,1]
      
      # padding (numpy friendly)
      max_len = max(color)
      vp_with_padding = [
          vp[sum(color[:i]):sum(color[:i])+l] + [0] * (max_len - l)
          for i, l in enumerate(color)
      ]
      # [[10, 20, 30], [40, 50, 0], [60, 0, 0]]
      total = np.sum(vp_with_padding, 1)
      # similar to:
      #total = [sum(x) for x in vp_with_padding]
      

      【讨论】:

        【解决方案3】:
        total = []
        index = 0
        for c in color:
          inside = 0
          for i in range(c):
            inside += vp[index + i]
            index += 1
          total.append(inside)
        print(total)
        

        【讨论】:

          【解决方案4】:

          使用列表推导 -

          vp = [10,20,30,40,50,60]
          color = [3,2,1]
          commu = np.cumsum(color)    # Get the commulative sum - [3,5,6]
          commu = list([0])+list(commu[0:len(commu)-1])    # [0,3,5] and these are the beginning indexes 
          total=[sum(vp[commu[i]:commu[i+1]]) if i < (len(range(len(commu)))-1) else sum(vp[commu[i]:]) for i in range(len(commu))]
          total
             [60, 90, 60]
          

          【讨论】:

            【解决方案5】:

            其他选项用切片构建一个列表,然后映射到总和:

            破坏性:

            slices = []
            for x in color:
              slices.append(vp[0:x])
              del vp[0:x]
            sums = [sum(x) for x in slices]
            
            print (sums) #=> [60, 90, 60]
            

            非破坏性:

            slices = []
            i = 0
            for x in color:
              slices.append(vp[i:x+i])
              i += x
            sums = [sum(x) for x in slices]
            
            print (sums) #=> [60, 90, 60]
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-09-14
              • 1970-01-01
              • 2012-08-07
              • 1970-01-01
              相关资源
              最近更新 更多