我在使用简单的Python脚本时遇到了麻烦.该脚本有一个温度列表输入,我想打印0到5之外的所有温度.
这工作正常,直到我输入浮点.例如,如果列表具有1,4,6,-2,则它仅按预期打印6和-2.如果我输入1,4,4.3,6,则打印出4.3和6.
我知道这个问题与浮点有关,并且出于某种原因,如果没有语句通过浮点数.虽然我确信这很简单,但我已经搜索了高低,但没有运气.
你知道为什么会这样吗?
# input for temperatures
temperatures = [1, 4, 4.3,6]
# empty output list
output_list = []
for temperature in temperatures:
if temperature not in range (0,6):
output_list = output_list + [temperature]
# print the output_list
print(output_list)
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助.
temperature not in range (0,6)表示温度不是其中一个值range(0,6),即0,1,2,3,4和5.
你真正想要检查的不是值是0,1,2,3,4,5中的一个,而是它是> = 0和<= 5.所以,这样做:
if not 0 <= temperature <= 5:
...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,为了更清楚地了解是什么range,试试这个:
>>> print(list(range(0, 6)))
[0, 1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
该range()功能默认只输出步长为1的数字.
例如,range(4)退货0, 1, 2, 3.将此比较与range(2, 4)哪些返回2, 3以及range(2, 4, 0.5)哪些返回2, 2.5, 3, 3.5.
对于您的问题,更好的解决方案将替换if temperature not in range (0,6):为if not 0 <= temperature <= 5:.
这是你的整个代码修复:
感谢@Bazingaa注意到错误.(感谢您的建议.append().)
# input for temperatures
temperatures = [1, 4, 4.3,6]
# empty output list
output_list = []
for temperature in temperatures:
if not 0 <= temperature <= 5:
output_list.append(temperature)
# print the output_list
print(output_list)
Run Code Online (Sandbox Code Playgroud)
请注意这里更简单的列表理解:
output_list = [temp for temp in temperatures if not 0 <= temperature <= 5]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40 次 |
| 最近记录: |