Skip to main content
 首页 » 编程设计

python之如何在不剥离以零结尾的非零值的情况下剥离这些 0 值

2025年05月04日16飞鱼

我正在处理心率数据,我想去掉当天心率从未达到的数字。

部分代码:

result_list = [ 
    '0 instances of 44 bpm',  
    '0 instances of 45 bpm',  
    '10 instances of 46 bpm',  
    '22 instances of 47 bpm',  
    '354 instances of 65 bpm',  
    '20 instances of 145 bpm' 
] 
 
strip_zero = [x for x in result_list if not '0 instances' in x] 
 
print(strip_zero) 

结果:

['22 instances of 47 bpm', '354 instances of 65 bpm'] 

如果我使用这个:'\'0 instances' 而不是这个:'0 instances'

0 个实例都没有被删除

请您参考如下方法:

改用startswith。

result_list = [ 
    '0 instances of 44 bpm',  
    '0 instances of 45 bpm',  
    '10 instances of 46 bpm',  
    '22 instances of 47 bpm',  
    '354 instances of 65 bpm',  
    '20 instances of 145 bpm' 
] 
 
strip_zero = [x for x in result_list if not x.startswith('0 instances')] 
 
print(strip_zero)