简体   繁体   中英

delete string with certain values from list in python

i have list

my_list = ['Cat Dog Tiger Lion', 'Elephant Crocodile Monkey', 'Pantera Cat Eagle Hamster']

i need to delete all of elements which containing sub = 'Cat'

so i need to have output

['Elephant Crocodile Monkey']

i think i need to do something with regex, maybe re.compile to find this values and then drop them from my_list ?

i have been tryed:

for string in my_list:
    if string.find(sub) is not -1:
        print("this string have our sub")
    else:
        print("sthis string doesnt have our sub")

but i dont know how to combine it with delete this rows from my_list

To filter lists, a simple approach is to use a list comprehension:

[i for i in my_list if 'Cat' not in i]
# ['Elephant Crocodile Monkey']

Which is equivalent to:

out = []
for i in my_list:
    if 'Cat' not in i:
        out.append(i)

Here's your list:

my_list = ['Cat Dog Tiger Lion', 'Elephant Crocodile Monkey', 'Pantera Cat Eagle Hamster']

You can use list comprehension for filtering the list:

new_list = [x for x in my_list if(not x.__contains__('Cat'))]

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