我正在处理心率数据,我想剔除那天心率从未达到的数字。
下面是一些代码:
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个实例均未删除
发布于 2019-07-17 03:18:13
请改用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)发布于 2019-07-17 03:21:27
您还可以拆分数字(第一个空格之前的任何内容)并检查它是否为零:
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'
]发布于 2019-07-17 03:27:37
我只会检查第一个字符是否等于'0',这样你就不必扫描每个字符串了。
strip_zero = [x for x in result_list if x[0] != '0']应该会更快,也更容易阅读。
https://stackoverflow.com/questions/57064040
复制相似问题