简体   繁体   中英

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

I have a list that is something like this:

output=['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/...." . Eg 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

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

if you have multiple strings need to be check, you may need this.

regex=re.compile('^/dev/mapper|^/usr/a')
filtered_list = [s for s in my_list if not re.match(regex, s)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM