Reputation: 42
TLDR: I want to print c at the bottom but to do that I have to make arrest and brest float. I cant do that
I've made a function that reads a file and separates the first line from the rest I have two files I'm using for this aaa.txt and bbb.txt then i try to manipulate the data. I try squaring each element of each string i realise I need to float it. I followed some guys advice but I still can't multiply stuff
is there any way I can make the brest or arrest into an array and rename them a_array. so i can just type a_array**2=h print(h) ?
but I'm really struggling to make it work. please copy and paste stuff and see if it works because I've been taking peoples suggestions for hours and nothing works. its 5 am I'm dying over here :(
aaa.txt is below
test a line 1
3,6,8,99,-4,0.6,8
0,9,7,5,7,9,5
2,2,2,2,2,2,5
7,5,1,2,12,8,0.9
bbb.txt is below
test b line 1
1,2,3,4,5,6,7,8
55,0,90,09,1,2,3,
8,9,7,6,8,7,6
3,43,5,8,2,4,1
def mi_func(P):
f=open(P, 'r')
first = f.readline()
restlines= f.readlines()
f.close()
return first, restlines
afirst,arest = mi_func('aaa.txt')
bfirst,brest = mi_func('bbb.txt')
#this ensures there are no standalone new line characters like ['\n', '5,6'..]
arest = [x for x in arest if x != '\n']
brest = [x for x in arest if x != '\n']
for i in range(len(arest)):
arest[i] = [float(x)**2 for x in arest[i].strip().split(',') if x != '\n']
for i in range(len(brest)):
brest[i] = [float(x) for x in brest[i].strip().split(',') if x != '\n']
print(arest)
c=(arest**2)+(brest**2)
print(c)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-629073a6846e> in <module>()
22 print(arest)
23
---> 24 c=(arest**2)+(brest**2)
25 print(c)
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
Upvotes: 0
Views: 59
Reputation: 1278
The issue was you were trying to square and add the list whereas you should perform math operations on individual float elements of the list. Here is your solution:
Modify the last part of your code to this:
c = arest[:] # this just clones arest into c
for i in range(len(arest)):
for j in range(len(arest[i])):
c[i][j] = (arest[i][j]**2)+(brest[i][j]**2)
print(c)
And c
should now have the sum of both the arrays squares!
Edit 1: If you now want to square C or do other math operations on it,
(i) either do
for i in range(len(c)):
for j in range(len(c[i])):
c[i][j] = c[i][j]**2
(ii) or you could do it at first time initialization itself in
c[i][j] = ((arest[i][j]**2)+(brest[i][j]**2))**2
Upvotes: 1
Reputation: 2322
what you are doing there is reading the same file twice,so restlines read the whole file and passes the fist line which is a string and it fails. there are better way to do what you are doing but following your context,this should fix the problem change this line
restlines= f.readlines()[1:]
Upvotes: 0