<分区>
我有以下问题:
我有一个列表:
temp= [950, 1000, 1100, 1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950, 2000, 2100, 2200]
在此列表中,我想删除所有 < 1200 and > 1950
的值.
我尝试了以下方法:
for x in temp:
if x < 1200 or x > 1950:
temp.remove(x)
这给了我以下结果:
[1000, 1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950, 2100]
但我的目标输出如下:
[1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950]
我找到了一种通过切片完成任务的方法:
new_temp = temp[temp.index(1200):temp.index(1950)+1]
这给了我想要的输出:
[1200, 1400, 1450, 1500, 1600, 1650, 1700, 1900, 1950]
但我想了解为什么 attemp1 不起作用,是否有比 attemp2
更好的方法来完成我的任务有人可以帮忙吗?提前致谢。