[問題] random 用 for 與 list 重複

看板Python作者 (Civil Jobs)時間6年前 (2019/04/04 20:25), 編輯推噓2(206)
留言8則, 4人參與, 6年前最新討論串1/1
簡單的程式碼,用Python 3 Jupyter Notebook import random List = [[0] * 3 ]*5 for m in range(0,5): for n in range(0,2): List[m][n] = random.randint(0,1) print(List) 得到 [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]] 欸不是,為什麼這樣會重複啦 害我只能寫很長一條來切...不然分段都會每段重複... -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.141.146.7 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1554380751.A.FF3.html

04/04 20:46, 6年前 , 1F
一開始建List的方法改掉就好
04/04 20:46, 1F

04/04 20:47, 6年前 , 2F
用list comprehension建吧
04/04 20:47, 2F

04/04 20:50, 6年前 , 3F
[[0 for _ in range(3)] for _ in range(5)]
04/04 20:50, 3F

04/04 21:34, 6年前 , 4F
你要不要用os.urandom自己轉換??
04/04 21:34, 4F

04/04 22:39, 6年前 , 5F
對欸 直接把random()丟在原本建立0但的地方就好了...
04/04 22:39, 5F

04/04 22:42, 6年前 , 6F
list = [random.randint(0,1) for _ in range ()]
04/04 22:42, 6F

04/05 00:49, 6年前 , 7F
list第2維不能用*5來建
04/05 00:49, 7F

04/05 01:30, 6年前 , 8F
對 我想也是因為會直接複製到一樣的位置 結果就...
04/05 01:30, 8F
文章代碼(AID): #1SfVVF_p (Python)
文章代碼(AID): #1SfVVF_p (Python)