2017-09-20 4 views
0

어떻게 목록의 키와 수치 값을 얻고 파이썬을 사용하여 자신의 배열에 배치합니까? 우는 소리는 지금까지 내 코드입니다 : 내가 현재 무엇입니까파이썬을 사용하여 목록에서 키와 값을 구분 하시겠습니까?

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 및 다른 사이트에 다른 자습서 및 기타 질문을 참조하는 시도했지만 아무것도이 스타일과 일치하는 것 같습니다.

+0

'all_w = [항목 [행의 항목] "w"]' –

+0

그렇다면 당신은 키와 값을 구분하려고? 'items' 객체에서? – Chinny84

답변

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)    
+2

약간의 설명은이 답변을보다 유용하게 만들 것입니다. –