2016-07-24 63 views
0

我們都知道我們可以將大量數據類型插入到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 
+0

您正在移除「對象」本身,形成您的列表,因爲您的列表中不包含您的對象什麼都不會改變。爲了獲得預期的輸出,您需要根據對象的屬性刪除項目。 – Kasramvd

+0

@Kasramvd是對的。你能描述一下Object.i的作用嗎? –

+0

對不起,這是我的錯誤。我編輯過的代碼現在清楚了嗎?代碼實際上不運行。但是我希望你明白我想要做什麼 – XChikuX

回答

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

您需要在最後一條語句中使用print來使其工作。謝謝,正是我想要的:D – XChikuX

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

尼斯拉達功能。但getattr()對我來說似乎更清潔。雖然謝謝:) – XChikuX

相關問題