在列表理解中有选择性的问题吗

2024-05-28 20:20:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用列表理解来将列表中的某些项目从摄氏度转换为华氏度。我有一份温度表。在这一点上我最好的猜测是这样的:

good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6]

但是我做的不对,我想不出来。你知道吗


Tags: to项目in列表foriftempgood
2条回答

你很接近。您需要的是:

good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]

如果temp大于9小于32.6,则此代码将只转换temp。对于超出该范围的temp值,不会向good_temps添加任何内容。你知道吗

temp已经是来自temperatures的项,因此temperatures[temp]没有太大意义,因为它试图使用temperatures的项作为索引。你知道吗

另一个答案中的另一个解决方案是使用过滤器获得子集:

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)]

相关问题 更多 >

    热门问题