I am trying to run my list though a function that I created, but keep getting errors. I don't know what is wrong.
Temperatures in F:
temp_f = [19, 21, 21, 21, 23]
Function:
def fahrToCelsius(tempFahrenheit):
return (tempFahrenheit - 32) /1.8
The function works, eg
fahrToCelsius(temp_f[1])
gives:
-6.111111111111111
But running it though a list doesn't. My attempt:
temp_c = []
for i in temp_f:
temp_c.append (fahrToCelsius(temp_f[i]))
print(temp_c)
Giving this error:
IndexError: list index out of range
I have tried a few different things, but nothing that I have tried works. Do you have any tips? Thanks.
最pythonic的解决方案是使用列表理解:
temp_c = [fahrToCelsius(t) for t in temp_f]
for i in temp_f
is actually assigning i to each element in your array, so 19, 21, etc. Therefore, temp_f[i]
is actually temp_f[19]
, which is why you are getting the error. Change the loop to:
for i in range(0, len(temp_f)):
temp_c.append (fahrToCelsius(temp_f[i]))
or instead:
for temp in temp_f:
temp_c.append (fahrToCelsius(temp))
Iterating the list using for i in temp_f
makes i
in this context refer to every item in your list.
What you want to do is iterate the list indices instead, like for i in range(len(temp_f))
.
Alternatively, you can iterate the list items like you did, but pass i
as the parameter to fahrToCelsius
(instead of temp_f[i]
).
If you want to use list as an input for this question as you are trying then use a numpy array instead of list , it will broadcast your conversion
import numpy as np
Lis= np.array([30,40,50])
def fahrToCelsius(tempFahrenheit):
return (tempFahrenheit - 32) /1.8
print(fahrToCelsius(Lis))
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.