简体   繁体   English

难以理解列表理解

[英]Having trouble with being selective in list comprehension

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. 该代码仅在大于9且小于32.6的情况temp才转换temp For temp values outside that range nothing will get added to good_temps . 对于超出该范围的temp值,不会将任何值添加到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. temp已经是来自temperatures的项,因此temperatures[temp]并没有多大意义,因为它试图将temperatures项用作索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM