1 回答

TA貢獻1830條經(jīng)驗 獲得超9個贊
我發(fā)現(xiàn)它更復雜,因為他們希望您在輸出中包含一個列表列表。添加到 my_list4 的每個元素本身都必須是一個列表。
如果作業(yè)是刪除所有列表推導式,則必須一次構(gòu)建一個子列表,然后將子列表添加到父列表中。像這樣:
for x in [20, 40, 60]:
sublist = [] # make an empty sublist
for y in [2, 4, 6]:
sublist.append(x*y) # put a single value into the sublist
my_list4.append(sublist) # add the completed sublist onto the parent list
雖然為了清晰起見,我更喜歡上述方法,但您也可以通過提前將空子列表添加到父列表中,并在添加值時不斷引用它來避免創(chuàng)建臨時列表:
for x in [20, 40, 60]:
my_list4.append([]) # append the empty sublist to the parent list
for y in [2, 4, 6]:
my_list4[-1].append(x*y) # use [-1] to reference the last item
# in my_list4, which is the current sublist.
您的嘗試是為 x 和 y 的每個組合創(chuàng)建一個單元素列表(每個單獨值周圍的方括號向您顯示這一點)。
添加回答
舉報