从列表中删除包含某些数据的对象
问题描述:
我们都知道我们可以将大量数据类型插入到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
答
我想你想要的是这样的:
>>> 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]
+0
您需要在最后一条语句中使用print来使其工作。谢谢,正是我想要的:D – XChikuX
答
对于列表
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)]
答
下列功能就会到位删除所有项目对他们的条件是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)]
+0
尼斯拉达功能。但getattr()对我来说似乎更清洁。虽然谢谢:) – XChikuX
您正在移除“对象”本身,形成您的列表,因为您的列表中不包含您的对象什么都不会改变。为了获得预期的输出,您需要根据对象的属性删除项目。 – Kasramvd
@Kasramvd是对的。你能描述一下Object.i的作用吗? –
对不起,这是我的错误。我编辑过的代码现在清楚了吗?代码实际上不运行。但是我希望你明白我想要做什么 – XChikuX