如何去掉这些0值而不去掉以0结尾的非零值?

2024-05-15 02:58:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理心率数据,我想去掉那些当天心率从未达到的数字。你知道吗

一些代码:

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个实例均未删除


Tags: of数据instances代码inforifnot
3条回答

您还可以拆分数字(第一个空格之前的任何数字)并检查它是否为零:

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'
]

改用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)

我只想检查第一个字符是否等于“0”,这样就不用扫描每个字符串了。你知道吗

strip_zero = [x for x in result_list if x[0] != '0']

应该更快,更容易阅读。你知道吗

相关问题 更多 >

    热门问题