John Smith
John Smith

Reputation: 1099

remove element if it has a certain string in it

I have a list ['1 2 4 5 0.9', '1 2 4 5 0.6', '1 2 4 5 0.3', '1 2 4 5 0.4']

I also have another list: [0.9, 0.3, 0.7, 0.8]

I want to use the second list and the first list elements include whats in the second list then the element gets removed, so the first list ends up like:

[1 2 4 5 0.6', '1 2 4 5 0.4']

Upvotes: 4

Views: 135

Answers (2)

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

Here is a more general approach to do this. I realize this may not be the best method to do this, but this was off the top of my head.

>>> listOne = ['1 2 4 5 0.9', '1 2 4 5 0.6', '1 2 4 5 0.3', '1 2 4 5 0.4']
>>> listTwo = [0.9, 0.3, 0.7, 0.8]
>>> finalList = []
>>> for element in listOne:
       flagBit = 0
       for number in element.split():
           if float(number) in listTwo:
               flagBit = 1
               break
       if flagBit == 0:
           finalList.append(element)

Upvotes: 0

mgilson
mgilson

Reputation: 309889

You mean something like this:

>>> lst = ['1 2 4 5 0.9','1 2 4 5 0.6','1 2 4 5 0.3','1 2 4 5 0.4']
>>> s = set([0.9,0.3,0.7,0.8])
>>> [x for x in lst if float(x.split()[-1]) not in s]
['1 2 4 5 0.6', '1 2 4 5 0.4']

Upvotes: 8

Related Questions