I have a function where I need to read every line that begins with the phrase "ABC", and for each ABC line there are xyz coordinates that follow it. How do I go about obtaining the average xyz coordinates overall by reading the correct line but not the actual ABC part itself?
So far I have the ability to print the lines but I'm confused on how to actually take them and the average Example line: "ABC 2.7826876194262695 5.6965460623956972 -2.4674016174576252" Code so far:
with open("filename",'r') as f:
for line in f:
if line.startswith("ABC"):
print(line)
CodePudding user response:
This? (untested)
with open("filename",'r') as f:
N = 0
X = 0
Y = 0
Z = 0
for line in f:
try:
start, x, y, z = line.strip().split()
if start == "ABC":
N = 1
X = float(x)
Y = float(y)
Z = float(z)
except:
pass
X /= N
Y /= N
Z /= N
CodePudding user response:
You can split on space and take everything after the first element.
sums = [0] * 3
points = 0
for line in f:
if line.startswith("ABC "):
points = 1
for i, x in enumerate(line.split()[1:]):
sums[i] = float(x)
avg = [s / points for s in sums]
print(avg)