J.Paul J.Paul - 2 months ago 14
Python Question

How can I find and remove elements that have a specific pattern from a list?

I have a list that is something like this:

list=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot', '/dev/mapper/vg00-lvol_data'.....]


I want to remove all the elements that has the format
"/dev/mapper/...."
.
E.g. here
list[1]='/dev/mapper/vg00-lvol_root'
. I tried using the index to remove(since in this case the odd no is occupied by the pattern. But that's not the case always). I then tried the logic of converting the elements to strings and then use regex to find the pattern. I thought of running a for loop to extract the list elements to individual strings(all that was complicated). I'm sure there must be an easier way to solve this

Answer
l=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot', '/dev/mapper/vg00-lvol_data']

filtered = [ x for x in l if "/dev/mapper/" not in x ]

print(filtered)

Output:

['Filesystem Size Used Avail Use% Mounted on', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot']

Comments