我正在处理心率数据,我想剔除当天心率从未达到的数字。
某些代码:
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个实例均未删除
答案 0 :(得分:6)
改为使用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)
答案 1 :(得分:0)
您还可以分割数字(第一个空格之前的任何数字)并检查其是否为零:
if __name__ == '__main__':
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'
]
non_zeros = [r for r in result_list if r.split(' ', 1)[0] != '0']
print(non_zeros)
输出:
[
'10 instances of 46 bpm',
'22 instances of 47 bpm',
'354 instances of 65 bpm',
'20 instances of 145 bpm'
]
答案 2 :(得分:0)
我只是检查第一个字符是否等于'0',从而使您不必扫描每个字符串。
strip_zero = [x for x in result_list if x[0] != '0']
应该更快,更容易阅读。
答案 3 :(得分:0)
使用简单的正则表达式尝试一下:
import re
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 re.search('^0 instances', x)]
print(strip_zero)