Home > Enterprise >  Inputting a list of numbers into a function?
Inputting a list of numbers into a function?

Time:09-27

I have a text file with a list of numbers all in one column for my input values, and want to use a defined function to spit out a list of output numbers. The function works fine as I tested with floating numbers, but I'm getting an error when inputting the list. What I have so far is:

#Read in text file 
text_file = open('example.txt', "r")

#Converting file into list
ex_list = text_file.readlines()
text_file.close()

#Defining function 
def f(x):
return (x - (5*math.log10(132)))

#Now inputting list of numbers into function 
f(ex_list)

But I'm getting an error saying "unsupported operand type(s) for -: 'str' and 'float'" which I'm assuming doesn't like the list format. I checked, and each value is a string of size 8, when I'm guessing should be an integer of size 1. So I didn't convert the list properly, any kind of help would be greatly appreciated.

CodePudding user response:

Assuming your example.txt file looks like this

0.772572
0.228697
9.053680
0.301091
0.051380

Then the following code will read in each line and convert the line to a number. The output will be a list of floats.

#Read in text file 
text_file = open('example.txt', "r")

#Converting file into list
ex_list = [float(line.strip()) for line in text_file]
text_file.close()

Your function will not work on a list of numbers, though. But you can map the function to the list. The result will be a list of the result of applying f() to each number in the file.

output = list(map(f, ex_list))

CodePudding user response:

Is this what you are trying to achieve?

import math

with open('example.txt') as fo:
    content = [int(i.strip()) for i in fo.readlines()]

def f(x):
    return (x - (5*math.log10(132)))


print([f(i) for i in content])

CodePudding user response:

f takes a float as an argument, not a list. So, instead of what you did, proceed like this:

First solution: Your function takes a list as an argument:

def f(L):
for i in L:
    print(float(i) - (5*math.log10(132))) #use print, not return!

Second solution: you call f on each element of your list

def f(x):
    return (x - (5*math.log10(132)))

fro i in ex_list:
    print(f(float(i)))

I hope that this will help

  • Related