【问题标题】:Split "weighted" list/array into equal size chunks将“加权”列表/数组拆分为大小相等的块
【发布时间】:2019-06-03 13:03:42
【问题描述】:

我有一组项目,每个项目都分配了权重。我想把它分成大约大小相等的块。相等的累积重量。这里有一个答案可以使用 numpy https://stackoverflow.com/a/33555976/10690958 有没有一种简单的方法可以使用纯 python 来完成这个?

示例数组:

[ ['bob',12],
 ['jack,6],
 ['jim',33],
....
]

a, 11
b,2
c, 5
d, 3
e, 3
f, 2

这里正确的输出是(假设需要 2 个块)

 [a,11],[b,2] - cumulative weight of 13

[c,5],[d,3],[e,3],[f,2] - cumulative weight of 13

为了进一步澄清这个问题,想象一下将 100 人分成 10 部电梯的情况,我们希望每部电梯都有相同的大约 10 部电梯。总重量(电梯中所有人的重量总和)。因此,第一个列表将成为名称和权重。这是一个负载平衡问题。

【问题讨论】:

  • 你能分享一个更大的示例数组吗?和预期输出
  • my_list = ["a", "foo", "booo", "qooo", "moo", "doo", "goo"] 块 = [my_list[x:x+2] for x in range(0, len(my_list), 2)] 会起作用,它会将项目放入配对的新列表中 - 我不确定我是否了解您的输入数据
  • 再次编辑以澄清。希望现在问题更清楚了

标签: python arrays sorting


【解决方案1】:

你只需要模仿cumsum:建立一个对权重求和的列表。最后你得到总重量。使用累积权重扫描列表,每次达到 total_weight/number_of_chunks 时创建一个新块。代码可能是:

 def split(w_list, n_chunks):
    # mimic a cumsum
    s = [0,[]]
    for i in w_list:
        s[0]+= i[1]
        s[1].append(s[0])
    # now scan the lists populating the chunks
    index = 0
    splitted = []
    stop = 0
    chunk = 1
    stop = s[0] / n_chunks
    for i in range(len(w_list)):
        # print(stop, s[1][i])     # uncomment for traces
        if s[1][i] >= stop:        # reached a stop ?
            splitted.append(w_list[index:i+1])    # register a new chunk
            index = i+1
            chunk += 1
            if chunk == n_chunks:                 # ok we can stop
                break
            stop = s[0] * chunk / n_chunks        # next stop
    splitted.append(w_list[index:])               # do not forget last chunk
    return splitted

【讨论】:

    【解决方案2】:

    你需要这样的拆分:

     array =[ ['bob',12],
     ['jack',6],
     ['jim',33],
      ['bob2',1],
     ['jack2',16],
     ['jim2',3],
      ['bob3',7],
     ['jack3',6],
     ['jim3',1],
     ]
    
    
    array = sorted(array, key= lambda pair: pair[1],  )
    
    summ = sum(pair[1] for pair in array )
    
    chunks = 4
    
    splmitt = summ // chunks
    
    print(array)
    
    print(summ)
    
    print(splmitt)
    
    def split(array, split):
    
        splarr = []
        tlist = []
        summ = 0
    
        for pair in array:
            summ += pair[1] 
            tlist.append(pair)     
            if summ > split:
                splarr.append(tlist)
                tlist = []
                summ = 0
    
    
    if tlist:
        splarr.append(tlist)
    return splarr
    
    spl = split(array, splmitt)
    
    import pprint 
    
    pprint.pprint(spl)
    

    【讨论】:

    • 谢谢。你的答案是正确的,除了一些拼写错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多