简体   繁体   中英

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

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.

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}

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 .
  • Python has a sum function that will sum up all the numbers in a list for you.
  • A couple of dict/list comprehensions would go a long way to simplifying things.

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. 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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