I need to use a list comprehension to convert certain items in a list from Celsius to Fahrenheit. I have a list of temperatures. What my best guess is at this point looks like this:
good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6]
However I'm not doing something right and I can't figure it out.
An alternative solution to the one pointed in another answer is to use filter to get the subset:
filter(lambda temp: 9 < temp < 32.6, temperatures)
Then a list comprehension to make the transformations:
[c_to_f(temp) for temp in temperatures]
Final expression:
good_temps = [c_to_f(temp) for temp in filter(lambda t: 9 < t < 32.6, temperatures)]
You're very close. What you need is:
good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]
This code will only convert temp
if it's greater than 9 and less than 32.6. For temp
values outside that range nothing will get added to good_temps
.
temp
is already an item from temperatures
, so temperatures[temp]
doesn't make much sense, since that's attempting to use an item of temperatures
as an index.
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.