Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表理解中有选择性的问题_Python_List Comprehension - Fatal编程技术网

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

Python 在列表理解中有选择性的问题,python,list-comprehension,Python,List Comprehension,我需要使用列表理解将列表中的某些项目从摄氏度转换为华氏度。我有一份温度表。在这一点上,我的最佳猜测如下: good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6] good_temps=[c_to_f(temp)表示温度中的温度,如果9

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

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

good_temps=[c_to_f(temp)表示温度中的温度,如果9
filter(lambda temp: 9 < temp < 32.6, temperatures)
最后一句话:

good_temps = [c_to_f(temp) for temp in filter(lambda t: 9 < t < 32.6, temperatures)]
good_temps=[c_至_f(temp)用于过滤器中的温度(λt:9
您非常接近。您需要的是:

good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]
good_temps=[c_to_f(temp)表示温度为9
此代码仅在大于9且小于32.6时转换
temp
。对于超出该范围的
temp
值,不会将任何内容添加到
good_temps


temp
已经是
temperatures
中的一个项目,所以
temperatures[temp]
没有多大意义,因为它试图使用
temperatures
的一个项目作为索引。

这似乎会将转换和未转换的temp混合到
good_temp
@tenwest,你是对的,我被他的“列表中的某些项”部分,但有选择地转换(在此上下文中)没有任何意义.啊,是的,我对这一部分感到困惑,现在我更好地理解了下一票哈,我很感激你不想让人们认为你在复制我的代码,但是
filter
在这里做得太过分了。这会使代码读起来更复杂,速度也更慢。@PM2Ring,绝对,这不仅仅是关于性能,它不是pythonic,因为有better(天然)在你的回答中指出的方式。我只是不想在这里复制:)我被困在工作中,但我不能告诉你我有多兴奋能回到它!非常感谢。我很高兴我很接近。我一直在<上遇到语法错误,它把我甩了。这是什么?我一直在用windows Powershell做每件事g在Python中。@user3650751 repl.it提供了一种使用Python(及其他语言)的方法当您有网络访问权限但没有在该设备上安装Python时。还有其他各种在线Python解释器,但repl.it是比较流行的解释器之一。另一个最受欢迎的是;它提供各种有趣的服务。如果下面的答案之一解决了您的问题,您应该接受它(单击相应答案旁边的复选标记)。这可以做两件事。它让所有人都知道您的问题已解决到令您满意的程度,并让帮助您的人相信您的帮助。有关完整的解释,请参阅。
good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]