从第一列和中间一列开始求一对列的和?

2024-04-24 12:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的意见:

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()

Tags: inimportforosnplinesqmath
2条回答

使用文件:

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方法:

用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

如果您希望在不使用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

相关问题 更多 >