2016-12-07 64 views
0

我有如下列表:使用列表解析從Python中的列表中刪除列表?

list = [['ab_c'], ['da_c'], ['da_b']] 

我想用列表解析從列表中刪除[「ab_c」]。 結果列表將是:

list = [['da_c'], ['da_b']] 

我嘗試使用下面的代碼:

new_list = [x for x in list if ['da_'] in x] 

但輸出在打印new_list是如下:

[] 

這是一個空的列表。 任何人都可以建議我如何滿足上述需求?

+1

1)不使用['list'](https://docs.python.org/ 3/library/functions.html#func-list)作爲名稱。 2)那麼'l = l [1:]'? 3)da_c不在'['da_c']'中。 – 2016-12-07 10:59:55

+0

仍然得到一個空的列表.. – user6730734

回答

3

我會將此解釋爲「選擇具有任何字符串其中的子列表與da_開始」:如果總是在子列表只是一個單一的元素

new_list = [x for x in list if any(s.startswith('da_') for s in x)] 

當然,它更容易:

new_list = [x for x in list if x[0].startswith('da_')] 
0

試試這個..

lis= [['ab_c'], ['da_c'], ['da_b']] 
new_list = [x for x in lis if any(s.startswith('da_') for s in x)] 
print new_list 

輸出:

[['da_c'], ['da_b']] 
0

嘗試這種情況:

list = [['ab_c'], ['da_c'], ['da_b']] 
new_list = [] 
for item in list: 
    if 'ab_c' not in item: 
    new_list.append(item) 

print new_list 
1
new_list = [x for x in l if 'da_' in x[0]] 

輸出:

[['da_c'], ['da_b']] 
+0

其中'l = [['ab_c'],['da_c'],['da_b']]' – jwdasdk