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

2024-05-16 01:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我们都很清楚,我们可以在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

Tags: the字符串列表objectitchthis字符
3条回答

我想你想要的是:

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

以下函数将在条件为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)]

为了名单

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

相关问题 更多 >