SoloistRoy SoloistRoy -4 years ago 88
Python Question

How is the variable changed in a function without being called?

def generateNew(data):

for i in range(len(data)-1):
data[i].append(data[i+1][2])
data[-1].append(oP)

for i in range(len(data)-1):
data[i].append(data[i+1][0])
data[i].append(data[i+1][1])
data[-1].append(hlP[0])
data[-1].append(hlP[1])

for i in range(len(data)-1):
data[i].append(data[i+1][4])
data[-1].append(volume)

new = [hlP[0], hlP[1], oP, cP, volume]
print new
return new

dataSet = []
for i in f.readlines():
i = i.split(',')
x = [float(j) for j in i[1:-1]]
x.append(int(i[-1]))
dataSet.append(x)
dataSet.reverse()
mData = dataSet # for next loop, append new set

for i in range(10):
temp = predictNew(mData)
print dataSet
dataSet.append(temp)
mData = dataSet


Here is my code.
dataSet
is like
[[1,2,3,4],[1,2,3,4]....]
, then I assign it to
mData
and pass it into the function
generateNew
(I remove some of the detail that are not necessary) and the list is now like
[[1,2,3,4,5,6],[1,2,3,4,5,6]....]
. However, I think neither
dataSet
nor 'mData' should be changed since all the changes happen inside the function, and the fact is not like that. Can anyone tell me why and improve that?
Thank you in advance.

Answer Source

If I understand you correctly, you are getting dataSet to change when you don't expect it to change. If this is the problem, then this issue is occurring in this line:

mData = dataSet # for next loop, append new set

To rectify this, I would look into Python's copy and deepcopy. When you 'copy' a list this way, it doesn't actually make another copy, but rather references the original. For example:

x = [1]
y = x
x.append(2)
x     #expected output is [1, 2] because we added 2 to this.
>>>[1, 2]
y     #y changes, even though it wasn't directly modified.
>>>[1, 2]

The easiest way to fix this is to use splice copying: y = x[:] However, this won't solve your issue because you have lists within lists. What you would need (I think) is deepcopy from the copy module. Let me know if I helped!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download