AD

2021-10-26

Python 建立 2D list

Python 建立 2D 串列時可以用3種方法:
1.直接建立:
new_list = [[0, 0, 0], [0, 0, 0]]
2. 用列表建立:
new_list = [[0 for r in range(3)] for c in range(2)]
3. 用 numpy建立陣列:
import numpy as np
new_list = np.zeros((3, 2), dtype=np.int)


如果用*來建立會遇到一些問題:
new_list = [[0] * 3]*2
看起來沒問題:
>>> new_list
[[0, 0, 0], [0, 0, 0]]

但如果
>>> new_list[0][1] = 1
>>> new_list
[[0, 1, 0], [0, 1, 0]]

用*建立出來的 2D list 是指向 list[0] 的 index,所以 list[0] 的值改變時,其他 list 也會更著改變。

沒有留言:

張貼留言

如果文章有幫助到你可以在 LikeCoin 上幫我拍手喔