首页 > 解决方案 > 如何从列表列表中的所有列表中删除元素?

问题描述

假设我有一个列表列表。

L = [[1,2,3], ['a',2,True],[1,44,33,12.1,90,2]]

我希望能够从列表 L 的每个子列表中删除特定元素的所有实例。

因此,例如,我可能想删除数字 2 这样会产生

L = [[1,3], ['a',True],[1,44,33,12.1,90]]

我尝试使用此功能+代码:

def remove_values_from_list(the_list, val):
    return [value for value in the_list if value != val]

for i in L:
    i = remove_values_from_list(i, '2')

但是输出仍然以原始形式给出 L 并且不会删除 2。

标签: pythonpython-3.xlist

解决方案


i是一个不连接到的变量L。它被分配了一个值L,然后你将它重新分配给其他东西;这根本不会影响L

一种非破坏性的方法(即保留L,为结果创建一个新列表):

newL = [[value for value in the_list if value != val] for the_list in L]

一种破坏性的方式(即改变L自己):

for the_list in L:
    while value in the_list:
        the_list.remove(value)

推荐阅读