2016-12-07 47 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