程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Error prone concept of two-dimensional list initialization in Python

編輯:Python

If you use Python Initializes a length of n One dimension of list, It's simple , just :

ls = [0] * n

The initialization element is n individual 0. But for two-dimensional , If you simply extend this method, it is easy to make mistakes :

ls = [[0] * n] * m

There will be problems . Put each dimension list As an element , The above code will only [[0] * n] Reference copy for m times , It won't open up m*n A unit of memory space to .

This is the time , Satisfy ls[0] With the address of ls[1],…, ls[m-1] Your address is exactly the same :

id(ls[0]) == id(ls[1])
# True

At this time , change ls[0] The value of will change to ls[1] The numerical .
I believe this initialization effect , Not the original intention of the coders ~

If necessary m*n What to do with a unit of memory space ?
as follows :

ls = [[0] * n for _ in range(m)]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved