使用python在列表中分隔键和值?

时间:2017-09-20 04:13:08

标签: python knapsack-problem

如何获取列表的键和数值并使用python将它们放在自己的数组中?到目前为止,贝娄是我的代码:

def make_chart(size, items): #this creates the grid
    keys = list(items.keys())
    chart = list()
    row = []
    for r in range(len(keys)):
        for i in range(size):
            row.append({"w":0, "v":0, "keys":[]})
        chart.append(row)
    return chart

def fill_chart(size, items, chart):
    keys = list(items.keys())
    values = list(items.values())
    weight = []
    #w, h = size +1, len(keys)


'''
here is where I need to separate the values for "w" and "v" and place them in their own arrays or lists that way I can fill the rest of the grid with zeros then try and run a Knapsack Problem on the information. 
'''


def main():
    iphone = {"w": 1, "v": 3000} #w is weight and v is value
    guitar = {"w": 1, "v": 2000}
    tablet = {"w": 2, "v": 3000}
    dog = {"w":1, "v": 4000}
    items = {"iphone":iphone, "guitar":guitar, "tablet":tablet, "dog":dog}

    chart = make_chart(4, items)
    chart = fill_chart(4, items, chart)


if __name__ == "__main__":
    main()

我正在获取(['w':1,'v'3000])当我打印出值时,我可以访问w值或v值,将它们放在自己的数组中使用。我已尝试在stackoverflow和其他网站上引用其他教程和其他问题,但似乎没有任何东西符合这种风格。

1 个答案:

答案 0 :(得分:0)

chart=chart[0]         
values=[[val[key] for val in chart] for key in chart[0]] # indexed values for each key. loop over list for each key.
w,v,key=values         

chart=chart[0]
val=zip(*[i.values() for i in chart])     #transpose list of values
w,v,key=map(list,val)