简体   繁体   English

总结一个浮点数列表(Python)

[英]Summing up a list of floats(Python)

The input file takes the format: 输入文件采用以下格式:

Britany     6.06 5.31 4.34 8.60 4.14 3.12 3.53 5.16
Eula        6.46 9.84 7.17 4.89 6.24 8.82 4.31 9.08
Georgianna  0.52 6.95 6.67 5.54 8.27 0.57 8.42 2.76
Serina      3.07 9.22 3.59 0.89 3.91 9.79 6.48 7.81

Here is my code so far: 到目前为止,这是我的代码:

empty={}
floatList=[]
infile= open(userOutputFile,'r',encoding='UTF8')
for line2 in infile:
    tempList2= line2.split()[1:]
    tempList2.remove(max(tempList2))
    tempList2.remove(min(tempList2))
for i in tempList2:
    tempList2 = float(i)
    floatList.append(tempList2)

What I tried to do is split the lines of file into a list of strings and then remove the max value and the min value. 我试图做的是将文件的行拆分为字符串列表,然后删除最大值和最小值。 That seems to be working, however, I am running into problems when trying to compute the sum for each line and then assigning that total to a dictionary with the corresponding name as the key and the value as the total. 这似乎是可行的,但是,当我尝试计算每一行的总和,然后将该总和分配给具有相应名称作为关键字并将值作为总和的字典时,我遇到了问题。 Basically the dictionary would read something like Britany(the key from the original file):43.01(the total computed). 基本上,字典将读取类似于Britany(原始文件中的键):43.01(计算出的总数)的内容。

Pandas is good for this: 熊猫对此有好处:

In [23]: import pandas as pd

In [24]: df = pd.read_table('t.txt', header=None, delimiter=' \w')

In [25]: df.sum(axis=1)
Out[25]:
0    2.26
1    3.81
2    4.70
3    4.76
dtype: float64

In [28]: dict(zip(df[0], df.sum(axis=1)))
Out[28]:
{'Britany    ': 2.2600000000000007,
 'Eula       ': 3.8099999999999996,
 'Georgianna ': 4.7000000000000002,
 'Serina     ': 4.7599999999999998}

In [29]: df.min(axis=1)
Out[29]:
0    0.06
1    0.08
2    0.27
3    0.07
dtype: float64

One thing that is immediately noticeable is that you separate the addition of the sum of the values from the to the dictionary from the actual iteration, and redefine the list each time. 立即注意到的一件事是,您将实际迭代中从到字典的值的总和相加,然后每次都重新定义列表。

For example: 例如:

empty={}
floatList=[]
infile= open(userOutputFile,'r',encoding='UTF8')
for line2 in infile:
    tempList2= line2.split()[1:]
    tempList2.remove(max(tempList2))
    tempList2.remove(min(tempList2))
print tempList2

And I get ['3.07', '9.22', '3.59', '3.91', '6.48', '7.81'], which are only the intermediate values of the last line. 我得到['3.07','9.22','3.59','3.91','6.48','7.81'],它们只是最后一行的中间值。

So you should rather do something like the following: 因此,您应该执行以下操作:

empty={}
infile= open(userOutputFile,'r').readlines()
for line2 in infile:
    name = line2.split()[0]    #Sets the name to be the initial value
    tempList2= line2.split()[1:]
    tempList2.remove(max(tempList2))
    tempList2.remove(min(tempList2))

    sum = 0

    for i in tempList2:
        i_val = float(i)
        sum += i_val      #Sums iteratively over each value in tempList2

    empty[name] = sum

Now do: 现在执行:

empty {'Georgianna': 30.759999999999998, 'Serina': 34.08, 'Eula': 42.66, 'Britany': 28.54} 空{'Georgianna':30.759999999999998,'Serina':34.08,'Eula':42.66,'Britany':28.54}

Same iteration sums the values and appends them to dictionary under the name. 相同的迭代将这些值相加,然后将其附加到名称下的字典中。

A few notes: 一些注意事项:

  • You should convert things to floats before eliminating the min and max. 您应该消除最小值和最大值之前将其转换为浮点数。 You're doing string comparisons right now, in which case "10.0" < "2.00" is True . 您现在正在进行字符串比较,在这种情况下, "10.0" < "2.00"True
  • Python has a sum function that will sum up all the numbers in a list for you. Python有一个sum函数,它将为您汇总列表中的所有数字。
  • A couple of dict/list comprehensions would go a long way to simplifying things. 几个dict / list 理解将大大简化事情。

This is what I came up with: 这是我想出的:

infile = open(userOutputFile,'r',encoding='UTF8')
lines = ( line.split() for line in infile )
result = { xs[0]: sum(sorted(map(float, xs[1:]))[1:-1]) for xs in lines }

The sum(sorted(map(float, xs[1:]))[1:-1]) part might be a bit hard to wrap one's head around. sum(sorted(map(float, xs[1:]))[1:-1])部分可能有点难缠。 This is what it does, from inside to outside: 这就是从内到外的作用:

  1. Grab all the numbers in the line (everything but the 1st entry) 抓取行中的所有数字(除第一个条目外的所有内容)
  2. Convert the numbers' string representations to floats 将数字的字符串表示形式转换为浮点数
  3. Sort the resulting floats 对产生的浮点数进行排序
  4. Grab all but the first and last (the min and max since it's sorted) 抓取除第一个和最后一个以外的所有内容(自排序以来的最小值和最大值)
  5. Sum them all up 全部加起来
f = open('input.txt', 'r')
d = f.read()
answers={}
for line in d.split("\n"):
    if len(line) > 0:
        line = line.split()
        #print(line)
        floats = [float(x) for x in line[1:]]
        floats.remove(max(floats))
        floats.remove(min(floats))
        name = line[0]
        x = sum(floats)
        #print(x)
        answers[name] = x

print(answers)

Gives the following output: 提供以下输出:

{'Eula': 42.66, 'Georgianna': 30.759999999999998, 'Britany': 28.54, 'Serina': 34.08}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM