简体   繁体   English

如何从列表中查找和删除具有特定模式的元素?

[英]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/...." .我想删除所有格式为"/dev/mapper/...."的元素。 Eg here list[1]='/dev/mapper/vg00-lvol_root' .例如这里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).我想运行一个 for 循环来将列表元素提取到单个字符串(所有这些都很复杂)。 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'] ['已使用的文件系统大小 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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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