简体   繁体   中英

Python- How To Remove Elements From a List Containing a Specific Word

I want to remove elements from a list containing a keyword.

For example-

list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']

I want to remove all elements in this list that contain "-test".

So the final output should be -->

list1= ["one", "two", "three"] #because if it contained '-test' we just deleted the element as a whole

Using list comprehension we can easily accomplish this goal. Also using in we can check if a key word is in any elements in the given list.

list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
newList = [elements for elements in list1 if '-test' not in elements]

output

['one', 'two', 'three']

Use list comprehension and check if the element of the list contains -test during iteration.

remove = '-test'
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
[x for x in list1 if remove not in x]
#['one', 'two', 'three']

The easiest way to get this done is

list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']

for l in list1:
    if '-test' in l:
        list1.remove(l)
list1  

Can also be done through list comprehenstion

res = []
for item in list1:
     if len(item.split("-")) <=1:
          res.append(item)
# res = ['one','two','three']

You can use a new array and split the given array. Append the values that satisfy the condition.

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