1

I am working with heart rate data and I want to strip away the numbers that the heart rate never reached for that day.

Some code:

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)

Result:

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

if I use this: '\'0 instances' instead of this: '0 instances'

none of the 0 instances are removed

pault
  • 41,343
  • 15
  • 107
  • 149
Jason Reed
  • 63
  • 6
  • 1
    You can use regular expressions with [word boundaries](https://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes). – pault Jul 16 '19 at 19:17
  • 1
    Possible duplicate of [Python regular expression match whole word](https://stackoverflow.com/questions/15863066/python-regular-expression-match-whole-word) – pault Jul 16 '19 at 19:18

3 Answers3

6

Use startswith instead.

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)
saarrrr
  • 2,754
  • 1
  • 16
  • 26
0

You can also split the number (anything before first space) and check if it's zero:

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)

output:

[
'10 instances of 46 bpm', 
'22 instances of 47 bpm', 
'354 instances of 65 bpm', 
'20 instances of 145 bpm'
]
abdusco
  • 9,700
  • 2
  • 27
  • 44
0

I would just check if the first character is equal to '0', saves you from having to scan every string.

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

Should be much quicker, and simpler to read really.