i'm having trouble code, have text file 633,986 tuples, each 3 values (example: first line -0.70,0.34,1.05
). want create array take magnitude of 3 values in tuple, elements a,b,c
, want magnitude = sqrt(a^2 + b^2 + c^2)
.
however, i'm getting error in code. advice?
import math fname = '\\pathname\\gerrystenhz.txt' open(fname, 'r') magn1 = []; in range(0, 633986): magn1[i] = math.sqrt((fname[i,0])^2 + (fname[i,1])^2 + (fname[i,2])^2) typeerror: string indices must integers, not tuple
you need use lines of file , csv
module (as martijn pieters points out) examine each value. can done list comprehension , with
:
with open(fname) f: reader = csv.reader(f) magn1 = [math.sqrt(sum(float(i)**2 in row)) row in reader]
just make sure import csv
well
to explain issues having (there quite few) i'll walk through more drawn out way this.
you need use open
returns. open
takes string , returns file object.
f = open(fname)
i'm assuming range in loop suppose number of lines in file. can instead iterate on each line of file 1 one
for line in f:
then numbers on each line, use str.split
method of split line on commas
x, y, z = line.split(',')
convert 3 float
s can math them
x, y, z = float(x), float(y), float(z)
then use **
operator raise power, , take sqrt of sum of 3 numbers.
n = math.sqrt(x**2 + y**2 + z**2)
finally use append
method add of list
magn1.append(n)
Comments
Post a Comment