python use of [[v] * n] * m encountered

Demand: to generate a matrix of m rows by n columns python

:( 1 way there is a problem)

data = [[0] * 3 ] * 4 # 4 rows and three columns 
data

  Export

[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

  Modifying data [0] [0] value of the element

data [0] [0] = 1 
time

  Export

[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]

  Wow, is not very crazy about the results, so why change a value of 0 would be classified as all the elements of change?

Analysis: We can look at them at the address corresponding to the memory

The problem here.

 

Option 2:

# Input 
DATAl = [[0 for I in Range (. 3)] for J in Range (. 4)] 
DATAl 

# Output 
[[0, 0, 0], [0, 0, 0], [0, 0, 0] , [0, 0, 0]] 


# inputs 
DATAl [0] [0] = 1 
DATAl 

# output 
[[1, 0, 0], [0, 0, 0], [0, 0, 0], [0 , 0, 0]]

  

Guess you like

Origin www.cnblogs.com/ivyharding/p/11402291.html