displaying celsius in python- functions [duplicate]
Possible Duplicate:
using functions to display numbers in a list
x = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,
29,40,36,24,26,30,30,32,34,32,28,36,24,32]
def fahrenToCel(x):
return (x - 32) * (5 / 9)
print fahrenToCel(x)
I know I have asked a couple of times, but I am still having issues. I just need to use a function to have that 开发者_开发技巧list of numbers displayed in celsius. This is the very last part I have to do, but I cannot figure it out. Please help
x = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,
29,40,36,24,26,30,30,32,34,32,28,36,24,32]
def fahrenToCel(x):
return (x - 32) * (5.0 / 9) # 5.0 to make result float (you can explicitly convert to float as well)
print [fahrenToCel(item) for item in x]
Unless x
is a numpy array, python will not know how to iterate over the values in x
. You need to either loop over the values in x and pass each element to fahrenToCel()
and place the returned value in a new list, or have fahrenToCel()
take a list and do the loop internally and return a new list.
You might want to look at the following chapter of the python tutorial:
http://docs.python.org/tutorial/controlflow.html
Or search for other examples of how to iterate through lists.
Update For example:
def stupidfunc(y):
return y
a = [1,2,3,4,5]
b = [stupidfunc(x) for x in a]
or
def stupidfunc2(y):
return [stupidfunc2(x) for x in y]
a = [1,2,3,4,5]
b = stupidfunc2(a)
What about you'd use map(fahrenToCel, x)
?
x = [30,34,40,36,36,28,29,32,34,44,36,35,28,33, 29,40,36,24,26,30,30,32,34,32,28,36,24,32]
def fahrenToCel(f_temp):
return (f_temp - 32) * (5.0/9)
celsius_list = map(fahrenToCel, x)
By the way, make sure you write 5.0/9
in your fahrenToCel
function since 5/9 == 0
Read about map function in python doc
精彩评论