我的输入:
a b c d e f
g h i j k l
我的输出应具有以下三种解决方案:
Sq( a**2 + d**2 ) + Sq ( g**2 + j**2 )
Sq( b**2 + e**2 ) + Sq ( h**2 + k**2 )
Sq( c**2 + f**2 ) + Sq ( i**2 + l**2 )
我的实际文本文件有很多行和列,没有标题。这是我到目前为止的内容:
import os
import math
import numpy as np
for file in os.listdir("directory"):
if file.endswith(".txt"):
fin=open(file, 'r')
total = 0
for line in fin:
str = [float(x) for x in line.split()]
for i in range(len(str[0:5])):
str[i]=float(str[i])
sum=np.sum((math.pow(str[i],2)+math.pow(str[i+3],2))**0.5
total += sum
fin.close()
答案 0 :(得分:1)
带有文件:
1 2 3 4 5 6
11 12 13 14 15 16
更正缩进和范围:
with open('stack53269737.txt') as f:
total = 0
for line in f:
str = [float(x) for x in line.split()]
for i in range(3):
str[i]=float(str[i])
sum=np.sum((math.pow(str[i],2)+math.pow(str[i+3],2))**0.5)
total += sum
In [111]: total
Out[111]: 73.84586902040324
进一步清理
with open('stack53269737.txt') as f:
total = 0
for line in f:
alist = [float(x) for x in line.split()]
for i in range(3):
total += (alist[i]**2+alist[i+3]**2)**0.5
我们不需要两次转换为float
;我们不需要math
用于简单的正方形。
一种麻木的方法:
使用numpy csv阅读器加载它:
In [126]: data = np.genfromtxt('stack53269737.txt')
In [127]: data
Out[127]:
array([[ 1., 2., 3., 4., 5., 6.],
[11., 12., 13., 14., 15., 16.]])
重塑数组以表示行拆分:
In [128]: data1 = data.reshape(2,2,3)
In [129]: data1
Out[129]:
array([[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[11., 12., 13.],
[14., 15., 16.]]])
现在我们可以对所有值求平方,在正确的轴上求和,取平方根再求和:
In [130]: np.sum(np.sum(data1**2, axis=1)**.5)
Out[130]: 73.84586902040324
答案 1 :(得分:0)
如果您希望在没有numpy
的情况下进行操作,则可以尝试以下操作:
import math
with open("data.txt", "r") as infile:
# Split the lines and then split numbers from each line.
lines = list(map(str.split, infile.read().split('\n')))
# Use zip to create tuples of values that take part in each operation.
lines = list(zip(*lines))
# Get length of each line.
lineLength = len(lines)
# Find the total.
total = sum([math.sqrt(int(lines[i][j])**2 + int(lines[i+3][j])**2) for i in range(lineLength-3) for j in range(2)])
print(total)
提供一个包含以下数据的文件:
1 2 3 4 5 6
7 8 9 10 11 12
结果是:
57.02450048972068