python - 如何从列表列表中的所有列表中删除元素?
问题描述
假设我有一个列表列表。
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。
解决方案
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)
推荐阅读
- azure - az 存储容器列表。不起作用,引用已删除的存储
- javascript - 打字稿从字符串中获取枚举值
- powerbi - Power BI 排序 - 隐藏排序列
- python - sqlalchemy 中嵌套序列化程序的问题
- javascript - 如何在 vue.js 的模板中获取 body html 元素?
- python - 如何链接在两个列表之间创建连接?
- computer-vision - 图像嵌入稀疏性
- java - 在 0mq 套接字上运行的 java 计时器线程的可能替代方案
- javascript - 使用 map、reduce、filter 为 JavaScript 优化嵌套循环
- python - {“title”:“不支持的媒体类型”,无论我尝试什么都会出错:I(