Why are these two values different when I assign one to the other?
The code below gives different values for c and d when I print them
import csv datafile = open('test1.csv', 'r')开发者_StackOverflow中文版 datareader = csv.reader(datafile) c = [] for row in datareader: c.append(row) d = [[0]*2]*2 i=0 while i < 2: j=0 while j < 2: d[i][j] = float(c[i][j]) j=j+1 i=i+1 print(c) print(d)
This line:
d = [[0]*2]*2
doesn't create copies of the inner lists, it just creates multiple references to the same list. Replace it with an explicit declaration:
d = [[0, 0], [0, 0]]
Lists are mutable elements. You're not creating multiple lists when you do things like [[0]]*10
but creates 10 references to the same object.
精彩评论