In the following code, when I print the row in the first loop after doing a bunch of manipulations with it I see the results that I want. However, after I exit the first loop, I find that I get a different result in the variable Dataset. I know this is a scoping issue but I cannot figure out what the problem is and how to get my desired result which is shown with the first “print” statement. Thanks for your help
import random
random.seed(1234567)
Key=[[.5,.5]]
Dataset=[[0]+[0]*1]*int(10/2) +[[1]+[0]*1]*int(10/2)
print "results I need"
for row in Dataset:
response=row[0]
for i in xrange(len(Key)):
if random.random() < Key[i][response]:
row[i+1]=response
else:
row[i+1]=1-response
print row
print "Results I get"
for row in Dataset:
print row
Datasetcontains multiple references to the common[0, 0]and[1, 0]sublists. (I’m also at a loss to understand why you’re making the initialization so complex.)You could fix this by using
[[0, 0] for i in xrange(5)] + [[1, 0] for i in xrange(5)].xrange).That looks like:
[i + 1]indexing is also clumsy. A simpler solution: start with a list of just the first values for the sublists, and within the loop, construct the rest of each sublist (we can do this with a list comprehension) and prepend the first element. Instead of replacing the elements of theDatasetin place, we can use another list comprehension to bind them together.That gives us: