即使没有更改,列表bin_bd
值也会更改;该程序用于从CSV文件中提取数据的分箱方法。我想尝试所有的分箱方法。
但该列表不断更新。那是为什么?
import random
import math
f=open('book3.csv','w')
for i in range(0,12):
e=str(random.randint(0,10))
f.write(e+'\n')
f.close()
z=[]
f=open('book3.csv','r+')
while True:
l=f.readline()
if not l : break
z.append(int(l))
f.close()
z.sort()
bin_out=[]
bin_mean=[]
bin_bd=[]
bin_no=input('Enter no of bins')
bsize=int (math.ceil(len(z)/bin_no))
print bsize
count=0
for i in range(bin_no):
bins1=[]
for j in range(bsize):
if(count<len(z)) :
print count
bins1.append(z[count])
count+=1
bin_out.append(bins1)
bin_mean.append(bins1)
bin_bd.append(bins1)
print "bins formed "
print bin_mean
print "Smoothing methods"
print bin_bd
binn1=[]
for i in bin_mean:
binn1.append(i)
print "By Mean"
p=[]
for i in range(len(bin_mean)):
k= sum(bin_mean[i])/bsize
p.append(k)
for i in range(len(binn1)):
for j in range(bsize):
binn1[i][j]=p[i]
print binn1
print "by Boundary "
p=[]
binn2=[[]]
print bin_bd
for j in range(0,4):
#print j
if (j==0 or j== bsize//1):
print " "
elif(j-0>j-bsize):
#print main[i][0]
binn2.append(bin_bd[i][0])
else:
binn2.append(bin_bd[i][bsize])
#print binn2
答案 0 :(得分:2)
当你这样做时:
bin_out.append(bins1)
bin_mean.append(bins1)
bin_bd.append(bins1)
所有三个列表都包含对相同bins1
列表的引用。然后你会做:
for i in bin_mean:
binn1.append(i)
所以binn1
也包含对相同列表的引用。最后,你这样做:
binn1[i][j]=p[i]
这会修改所有4个变量所引用的列表。
您应该复制清单:
bin_out.append(bins1[:])
bin_mean.append(bins1[:])
bin_bd.append(bins1[:])
...
for i in bin_mean:
binn1.append(i[:])
顺便说一下,这个循环可以用列表理解来完成:
binn1 = [i[:] for i in bin_mean]