Reputation: 844
We are all well aware that we can insert a vast array of datatypes into a python list. For eg. a list of characters
X=['a','b','c']
To remove 'c' all i have to do is
X.remove('c')
Now What I need is to remove an object containing a certain string.
class strng:
ch = ''
i = 0
X = [('a',0),('b',0),('c',0)] #<---- Assume The class is stored like this although it will be actually stored as object references
Object = strng()
Object.ch = 'c'
Object.i = 1
X.remove('c') #<-------- Basically I want to remove the Object containing ch = 'c' only.
# variable i does not play any role in the removal
print (X)
[('a',0),('b',0)] #<---- Again Assume that it can output like this
Upvotes: 0
Views: 84
Reputation: 6288
The following function will remove in place all the items for them condition is True
:
def remove(list,condtion):
ii = 0
while ii < len(list):
if condtion(list[ii]):
list.pop(ii)
continue
ii += 1
Here how you can use it:
class Thing:
def __init__(self,ch,ii):
self.ch = ch
self.ii = ii
def __repr__(self):
return '({0},{1})'.format(self.ch,self.ii)
things = [ Thing('a',0), Thing('b',0) , Thing('a',1), Thing('b',1)]
print('Before ==> {0}'.format(things)) # Before ==> [(a,0), (b,0), (a,1), (b,1)]
remove( things , lambda item : item.ch == 'b')
print('After ==> {0}'.format(things)) # After ==> [(a,0), (a,1)]
Upvotes: 1
Reputation: 174624
I think what you want is this:
>>> class MyObject:
... def __init__(self, i, j):
... self.i = i
... self.j = j
... def __repr__(self):
... return '{} - {}'.format(self.i, self.j)
...
>>> x = [MyObject(1, 'c'), MyObject(2, 'd'), MyObject(3, 'e')]
>>> remove = 'c'
>>> [z for z in x if getattr(z, 'j') != remove]
[2 - d, 3 - e]
Upvotes: 1
Reputation: 1425
For the list
X = [('a',0),('b',0),('c',0)]
If you know that the first item of a tuple is always a string, and you want to remove that string if it has a distinct value, then use a list comprehension:
X = [('a',0),('b',0),('c',0)]
X = [(i,j) for i, j in X if i != 'c']
print (X)
Outputs the following:
[('a', 0), ('b', 0)]
Upvotes: 0