__ Rows (n1) and columns (n2) are entered in the first row, and n2 columns. Or # are entered in the second and subsequent rows. Store the character strings on the second and subsequent lines n1 in a two-dimensional array. __
Give the following input data as an example
3 5
#####
.#.#.
#.#.#
#Enter the rows and columns of the array to be created separated by spaces
in1 = input()
arr1=in1.split()
#Next to arr1 specified above[1]The character string for the column is arr1[0]Read line text
in2=[]
for i in range(int(arr1[0])):
tmp1=input()
in2.append(tmp1)
#The following two-dimensional array(arr1[0]Line arr1[1]Column)Create
arr2=[[''] * int(arr1[1]) for i in range(int(arr1[0]))]
arr3=[['']*int(arr1[1])]*int(arr1[0])
#Display the 2D array defined above
print(arr2)
print(arr3)
for i in range(int(arr1[0])):
tmp2=in2[i]
for j in range(int(arr1[1])):
arr2[i][j]=tmp2[j:j+1]
arr3[i][j]=tmp2[j:j+1]
print(arr2)
print(arr3)
[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']]
[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']]
[['#', '#', '#', '#', '#'], ['.', '#', '.', '#', '.'], ['#', '.', '#', '.', '#']]
[['#', '.', '#', '.', '#'], ['#', '.', '#', '.', '#'], ['#', '.', '#', '.', '#']]
In the first and second lines, the initialized two-dimensional array data is displayed. What we pay attention to is the difference between the execution results of the 3rd and 4th lines `__.
The values in all the arrays of arr3 have been replaced with the data in the last row of input.
Refer to Initialize Python list (array) with arbitrary value / number of elements Add the following code to the above code.
print(arr2[0]==arr2[int(arr1[0])-1])
print(arr3[0]==arr3[int(arr1[0])-1])
False
True
Because the list of elements in arr3 are all treated as the same object It seems that when one list is updated, the other lists are updated with the same contents.
When declaring a two-dimensional array with initial values
List name = [[Initial value] * Number of columns for Arbitrary variable in range (number of rows)]
use.
Recommended Posts