簡體   English   中英

使用列表推導從python中的列表中刪除列表?

[英]Deleting a list from a list in python using list comprehensions?

我有如下列表:

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時的輸出如下:

[]

這是一個空清單。 誰能建議我如何滿足上述需求?

我將其解釋為“選擇其中包含以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_')]
new_list = [x for x in l if 'da_' in x[0]]

輸出:

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

嘗試這個..

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']]

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM