从列表中删除包含特定数据的对象

时间:2016-07-24 18:18:18

标签: python python-3.x

我们都很清楚我们可以将大量数据类型插入到python列表中。例如。一个字符列表

X=['a','b','c']

要删除'c',我所要做的就是

X.remove('c')

现在我需要删除一个包含某个字符串的对象。

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

3 个答案:

答案 0 :(得分:1)

我认为你想要的是:

>>> 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]

答案 1 :(得分:1)

以下功能会删除到位所有项目的条件为True

def remove(list,condtion):
    ii = 0
    while ii < len(list):
        if condtion(list[ii]):
            list.pop(ii)
            continue        
        ii += 1

在这里您可以使用它:

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)]

答案 2 :(得分:0)

列表

X = [('a',0),('b',0),('c',0)] 

如果您知道元组的第一项始终是字符串,并且您想要删除该字符串(如果它具有不同的值),则使用列表推导:

X = [('a',0),('b',0),('c',0)] 

X = [(i,j) for i, j in X if i != 'c']

print (X)

输出以下内容:

[('a', 0), ('b', 0)]