python - Array sizes being added instead of staying constant -
i wish add contents of multiple arrays in single array, go on different files store data in array , add them, data seems getting appended rather being added. example want, a=[1,2,3,4], b=[2,3,4,5],c=[3,4,1,2] , final array sum=[6,9,8,11]. reason not able perform operation! know stupid mistake somewhere!
x=[] s=[] s=[] p=[] p=[] d=[] d=[] #print 'starts0 %f' % s[0] #print 'starts1 %f' % s[1] n=3 in xrange(1,n+1,1): stri = str(i) dos_file =open("dos"+stri,"r") #dos_file =open("dos1","r") print 'filename %s' % dos_file line_aa in dos_file.readlines(): line_aa=line_aa.split() #x=[0]*1000 #p=[0]*1000 x.append(line_aa[0]) s.append(line_aa[1]) #p.append(line_aa[2]) #d.append(line_aa[3]) #dos_file.close() x=[float(i) in x] s=[float(i) in s] print 's0 %f' % s[998] print 's1 %f' % s[999] sizes=len(s) print 'sizes %d' % sizes s=[0]*sizes print 's0 %f' % s[0] print 's1 %f' % s[1] sizes=len(s) print 'sizes %d' % sizes #dos_file.close() s_tot=[a + b a, b in zip(s, s)] print 's_tot0 %f' % s_tot[0] print 's_tot1 %f' % s_tot[1] sizes_tot=len(s) print 'sizes_tot %d' % sizes_tot dos_file.close() #x=[0]*sizes #p=[0]*sizes print 'ends0 %f' % s_tot[0] print 'ends1 %f' % s_tot[1]
the result is:
filename <open file 'dos1', mode 'r' @ 0x2aaaabe06540> sizes 1000 sizes 1000 sizes_tot 1000 filename <open file 'dos2', mode 'r' @ 0x2aaaabe065d0> sizes 2000 sizes 2000 sizes_tot 2000 filename <open file 'dos3', mode 'r' @ 0x2aaaabe06540> sizes 3000 sizes 3000 sizes_tot 3000
the operation want this:
a = [1, 2, 3, 4] b = [2, 3, 4, 5] c = [3, 4, 1, 2] print([sum(items) items in zip(a, b, c)])
results in
[6, 9, 8, 11]
here, i'm using list comprehension, sum, , zip.
Comments
Post a Comment