Auer3212
Auer3212

Reputation: 29

How do you use sum () with list items?

I am trying to create a program which prints the mean of certain values in a file. When I run my code using the file 'cropdata.txt', which contains this:

Lettuce 1 2 3 
Tomato 6 5 1 

I get the following error:

    line_mean = (sum(line_parts[1:])/len(line_parts))
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

I am not really sure why this is as I thought that I had converted the selected elements to integers.

My code:

file = ('cropdata.txt')
with open(file, 'r') as file_numsort_1:
    for line in file_numsort_1:
        line = (line.rstrip(" \n"))
        line_parts = line.split(' ')
        for num in line_parts[1:]:
            num=int(num)
        line_mean = (sum(line_parts[1:])/len(line_parts))
        print(line_mean) 

Upvotes: 1

Views: 56

Answers (3)

wnnmaw
wnnmaw

Reputation: 5534

Your code

for num in line_parts[1:]:
    num=int(num)

isn't really doing anything, as the variable num gets overwritten each iteration of the loop. Therefore, none of the data is converted from str to int type which is the cause of your error. What you want to do is create a list of numbers as such:

file = ('cropdata.txt')
with open(file, 'r') as file_numsort_1:
    for line in file_numsort_1:
        line = (line.rstrip(" \n"))
        line_parts = line.split(' ')

        num_list = []
        for num in line_parts[1:]:
            num_list.append(int(num))

        line_mean = sum(num_list)/float(len(num_list))

A few other things to note:

  • Using line.split(' ') is a little superfluous as line.split() will automatically split whitespace delimiters. It also counts consecutive spaces as one delimeter
  • No argument is needed in line = line.rstrip() and you certainly don't need the enclosing parenthesis
  • I've added a float() function to your line_mean calculation. In Python 2, operations on two integers stay as an integer (so 5/3 = 1, not 1.66). I believe Python 3 has similar behavior but this extra function doesn't hurt if not (Thanks for the clarification Bharel), this float function is not needed in Python 3

Upvotes: 1

Bharel
Bharel

Reputation: 26941

Upon converting like this num=int(num), you didn't save the conversion back in the list.
Try converting like so:

line_parts = [int(x) for x in line_parts[1:]]

and then sum like so:

line_mean = (sum(line_parts)/len(line_parts))

Alternatively you may use the statistics module instead of summing yourself.


An optimized version:

import statistics

file = ('cropdata.txt')
with open(file, 'r') as file_numsort_1:
    for line in file_numsort_1:
        # Strip, split, and convert to int
        line_ints = map(int, line.rstrip().split()[1:])

        # Print the mean
        print(statistics.mean(line_ints)) 

Upvotes: 1

trinchet
trinchet

Reputation: 6933

Your problem is not with sum but the list of 'numbers', this should solve your problem:

line_parts = line.split(' ')
list_of_nums = [int(item) for item in line_parts[1:]]
line_mean = (sum(list_of_nums)/len(C))
print(line_mean) 

Upvotes: 0

Related Questions