2024-05-28 20:20:55 发布
网友
我需要使用列表理解来将列表中的某些项目从摄氏度转换为华氏度。我有一份温度表。在这一点上我最好的猜测是这样的:
good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6]
但是我做的不对,我想不出来。你知道吗
你很接近。您需要的是:
good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]
如果temp大于9小于32.6,则此代码将只转换temp。对于超出该范围的temp值,不会向good_temps添加任何内容。你知道吗
temp
good_temps
temp已经是来自temperatures的项,因此temperatures[temp]没有太大意义,因为它试图使用temperatures的项作为索引。你知道吗
temperatures
temperatures[temp]
另一个答案中的另一个解决方案是使用过滤器获得子集:
filter(lambda temp: 9 < temp < 32.6, temperatures)
然后列出进行转换的步骤:
[c_to_f(temp) for temp in temperatures]
最终表达式:
good_temps = [c_to_f(temp) for temp in filter(lambda t: 9 < t < 32.6, temperatures)]
你很接近。您需要的是:
如果
temp
大于9小于32.6,则此代码将只转换temp
。对于超出该范围的temp
值,不会向good_temps
添加任何内容。你知道吗temp
已经是来自temperatures
的项,因此temperatures[temp]
没有太大意义,因为它试图使用temperatures
的项作为索引。你知道吗另一个答案中的另一个解决方案是使用过滤器获得子集:
然后列出进行转换的步骤:
最终表达式:
相关问题 更多 >
编程相关推荐