看板 Python 關於我們 聯絡資訊
小弟新學Python~ 先前在迴圈內使用list.append在list中append list output出來的值 不知為何會一直重複 並沒有依序加在list的最尾端 請教各位大大~小弟是哪個地方沒有注意到 Output: Loop 1 Need to add [-1, 0, 1] Result [[-1, 0, 1]] Loop 2 Need to add [-1, 0, 1] Result [[-1, 1, 0], [-1, 1, 0]] Loop 3 Need to add [-1, -1, 2] Result [[-1, 2, -1], [-1, 2, -1], [-1, 2, -1]] . . . . //////////////////////////////////////////////////////////////////// Code: nums = [-1, 0, 1, 2, -1, -4] if len(nums) < 3: final_answer_list = [] else: answer_list = [0,0,0] final_answer_list = [] print(final_answer_list) input_length = len(nums) z = 0 for i in range(0,input_length): for j in range(0,input_length): if j!=i: for k in range(0,input_length): if k!=i and k!=j: answer_list[0] = nums[i] answer_list[1] = nums[j] answer_list[2] = nums[k] cum_val = 0 for l in range(0,3): cum_val += answer_list[l] if cum_val == 0: z += 1 print('Loop',z) answer_list2 = sorted(answer_list) print('Need to add ',answer_list2) final_answer_list.append(answer_list) print('Result ',final_answer_list) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.1.232.147 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1505449286.A.2CD.html
Yshuan: final_answer_list.append(list(answer_list)) 09/15 14:34
Yshuan: append進去的一直是同一塊記憶體 需要copy出來 09/15 14:35
cutekid: 推樓上(Y) 09/15 14:40
brightwish: 不對吧 你打need to add answer_list2 可是你append的 09/16 00:26
brightwish: 是answer_list阿... 漏打2吧? 09/16 00:26
pd41987: 感謝一樓大大!! 剛試過沒有問題 List如預期append起來了 09/16 21:20
brightwish: 樓上 我剛測過了 你就是漏打2啦 09/17 02:33