2013-12-16 81 views
0

我名單由一個字典:從其減去元素

>>> triplets.get(k) 
[[1, 3, 15], [1, 3, 13], [1, 3, 11], [1, 3, 9], [1, 3, 8], [1, 3, 5], [1, 4, 15] 

,並字典:

>>> cset1.get(k) 
[set([5])] 

>>> cset2.get(k) 
[[1, 8], [1, 9], [1, 11]] 

我想刪除其中包含的cset1或兩個元素三胞胎的元素cset2的元素,即我想刪除[1,3,5]其中包含[5][1, 3, 8], [1, 3, 9], [1, 3, 11]其中包含cset2的元素。

我有下面這段代碼(這並不做任何事情):

CDln = len(triplets.get(k)) 

for ii in range(CDln): 
    if cset1.get(k) in triplets.get(k)[ii] or cset2.get(k) in triplets.get(k)[ii]: 
    print "delete element of triplets in location:", ii 

我無法弄清楚如何從字典triplets刪除這些內容(我用的是print語句作爲虛擬我想要的)。

+1

你能解釋一下你打算實現與這個數據structe或從那裏出現什麼呢?只是爲了避免X-Y問題。 – Hyperboreus

+0

@Hyperboreus,什麼是X-Y問題? –

+1

@PaulDraper問一個關於X的問題,試圖解決Y. – Hyperboreus

回答

1

我不太清楚,如果我給你的權利,但看看和意見,請:

k = 42 #whatever 
triplets = {k: [[1, 3, 15], [1, 3, 13], [1, 3, 11], [1, 3, 9], [1, 3, 8], [1, 3, 5], [1, 4, 15]]} 
cset1 = {k: [set([5])]} 
cset2 = {k: [{1, 8}, {1, 9}, {1, 11}]} #changed this to sets 

triplets[k] = [x for x in triplets[k] if 
       all (y - set(x) for y in cset1[k]) and 
       all (y - set(x) for y in cset2[k]) 
       ] 
print(triplets[k]) 
+0

謝謝Hyperboreus。我沒有問題的運行你的代碼,但是當我使用我的數據時,它會迴應:TypeError:不支持的操作數類型爲 - :'list'和'set'。我不明白爲什麼,因爲cset1,cset2和triplets被定義爲字典。 – Augusto

+0

我已將cset2(爲了與cset1中的結構相同)轉換爲集列表的字典,而不是列表的列表。請參閱我的代碼中的評論。但是你可以簡單地用'set(y) - set(x)'替換最後一個'y - set(x)'。 – Hyperboreus

0

我不知道什麼是ii,但我認爲這是你想要的。

b = cset1[k] 
c = cset2[k] 
triplets[k] = filter(
    lambda lst: 
     any(lambda x: x in b, lst) or 
     any(lambda c1: all(lambda x: x in c1), c), 
    triplets[k] 
] 

但是:

我不知道爲什麼你有一個cset1cset2。它好像,你應該有cset2,其值是

[[5], [1, 8], [1, 9], [1, 11]] 
+0

謝謝保羅。我跑了你的一段代碼,它回答:'錯誤:任何()只需要一個參數(給出2)' – Augusto