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

Explain in detail the initialization of Python one-dimensional and two-dimensional lists

編輯:Python

Catalog

Initialization of one-dimensional list :

Initialization of two-dimensional list :

Initialization of one-dimensional list :

The initial length is 5 A list of

The way 1:

a = [0]*5# [0, 0, 0, 0, 0]

The way 2:

a = [0 for _ in range(5)]# [0, 0, 0, 0, 0] Initialization of two-dimensional list :

The first one 2*5 A list of :

The way 1:

b = [[0]*5 for _ in range(2)]# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

The way 2:

b = [[0 for _ in range(5)] for _ in range(2)]# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Be careful :

The following is wrong , This is equivalent to taking [0]*5 This one-dimensional list duplicates 2 Time , Whenever you change an element in one of the one-dimensional lists , The elements in the rest of the list will also change .

b = [[0]*5]*2# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]b[0][1] = 3 # [[0, 3, 0, 0, 0], [0, 3, 0, 0, 0]]

This is about python ( A one-dimensional 、 A two-dimensional ) This is the end of the list initialization article , More about python For the initialization content of the list, please search the previous articles of the software development network or continue to browse the relevant articles below. I hope you can support the software development network in the future !



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