2017-10-23 4 views
0

파이썬에서 for 루프를 사용하여 사전을 만들고 싶습니다. 여기서 각 키 (내 경우 CUI)는 값 배열과 연관되어 있지만 얻은 결과는 각각 사전입니다 키가 내 목록에있는 값 중 하나에 불과합니다. 내 코드에 따라 :for 루프 파이썬에서 사전

import numpy as np 
data2 = open('pathways.dat', 'r', errors = 'ignore') 
pathways = data2.readlines() 

special_line_indexes = [] 
line_cont = [] 
L_PRMR = [] #Left primary 
dict_comp = dict() 

#i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate) 
for CUI in just_compound_id: 
    PWY_ID = [] 
    for i,line in enumerate(pathways): 
     if '//' in line: 
      #fint the indexes of the lines containing // 
      special_line_indexes = i+1 
     elif 'REACTION-LAYOUT -' in line: 
      if CUI in line: 
       PWY_ID.append(special_line_indexes) 
    dict_comp[CUI] = PWY_ID 
print(PWY_ID) 
print (dict_comp) 

편집 당신이 이상의 값을을 writting 때문에 그것의 이유 :

import numpy as np 
data2 = open('pathways.dat', 'r', errors = 'ignore') 
pathways = data2.readlines() 

special_line_indexes = [] 
PWY_ID = [] 
line_cont = [] 
L_PRMR = [] #Left primary 
dict_comp = dict() 

#i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate) 
for CUI in just_compound_id: 
    for i,line in enumerate(pathways): 
     if '//' in line: 
      #fint the indexes of the lines containing // 
      special_line_indexes = i+1 
     elif 'REACTION-LAYOUT -' in line: 
      if CUI in line: 
       PWY_ID.append(special_line_indexes) 
       dict_comp[CUI] = special_line_indexes 
print(PWY_ID) 
+1

'dict_comp의 [의 CUI]와 시간 = special_line_indexes'에 대한 내부 전에 빈 상태 (empty)의 배열이,'dict_comp의 [의 CUI] = PWY_ID'해야한다 '. 또한 구조에 따라 for 루프의 어딘가에서이 목록을 삭제해야합니다. – ZdaR

답변

2

당신의 내부에서 사전을하고 PWY_ID 테이블을 asign 필요 사전 값 (CUI)은 값 배열 대신 값 (special_line_indexes)을 갖습니다. 필요한 것은 내부 (for PWY_ID(append))에 대한 테이블을 생성하고, 각 루프에 하나의 요소를 추가하고, 일단 for 루프를 완료하면 해당 배열을 사전에 할당해야합니다 (dict_comp [CUI] = PWY_ID). 당신이 PWY_ID`에 가치를 추가 되었기 때문에

당신은 각 PWY_ID = []

+0

왜이 두 단계가 필요한지 설명해 주시겠습니까? – StudentOIST

+0

내 대답에 덧글을 추가했습니다. 이유를 설명하기를 바랍니다. – nacho