作爲使用Python的初學者,我試圖使用if語句使用值填充字典。如果您有任何意見,爲什麼這不起作用,我會很感激您的意見。馬哈洛提前!從列表中使用條件填充字典
#first list
groslist = [0, 1, 2, 3]
#dictionary whose keys are items in grosList
grosdict = {k:[] for k in groslist}
#second list whose items correspond with dictionary's keys
indivlist = [0, 0, 1, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3]
#third list whose nth item ID corresponds indivlist
indivIDlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#Populate dictionary with indivIDlist values (dict keys correspond with indivlist items)
for ID in indivlist:
for ID in groslist:
x = 0;
if indivlist[x] == groslist[x]:
grosdict[indivlist[x]] = indivIDlist[x];
x += 1
這裏是我的理想輸出:
print CG_IDdict
{0: [0, 1, 3], 1: [2, 4, 5, 6], 2: [7, 8, 9, 10], 3: [11, 12]}
初學者的不錯代碼:D –
什麼是'CI_refCG_IDlist','CG_IDlist'和'CG_IDdict'? –
沒有太多的分析。對於外部循環和內部循環,您都使用變量'ÌD'。這可能是問題所在。 (nvm,你甚至沒有使用變量) – M4rtini