fuk
fuk

Reputation: 23

Troubleshooting, cannot convert my list of floats into a string

I have a function that reads in a file and processes the data, which I need to write into a new file. However, I cannot put the data into a file because it is not in the string format even though I thought I had converted it to a string in the function? Have I overlooked something or do I need to add more code?

def process_data(data_file):
    data = open(data_file, "r") 
    next (data)
    for line in data:
        line = line.rstrip()
        m = line.split("\t")
        x = m[2:]
        numbers = [float(i) for i in x]
        avg = [float(sum(numbers))/len(numbers)]
        max_num = [max(numbers)]
        min_num = [min(numbers)]
        main_list = avg + max_num + min_num
        values = [str(i) for i in main_list]
        print('\t'.join(map(str,values)))

The error I get when I try to write it is "argument must me str not None"

write(process_data(data_file))

Upvotes: 0

Views: 19

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140226

your function returns None. Don't print your return value, just accumulate to a list of strings then return it joined by linefeed in the end (that avoids string concatenation which is inefficient)

I also fixed some clumsy list creation and removed one unnecessary cast to str (done twice).

def process_data(data_file):
    retval = []
    data = open(data_file, "r") 
    next (data)
    for line in data:
        line = line.rstrip()
        m = line.split("\t")
        x = m[2:]
        numbers = [float(i) for i in x]
        values = [float(sum(numbers))/len(numbers),max(numbers),min(numbers)]
        retval.append('\t'.join(map(str,values)))
   return "\n".join(retval)

Note that using the csv module as reader and writer would be a lot better, would save you a lot of split, join, str conversions... But that's more a job for CodeReview.

Upvotes: 1

Related Questions