社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python 3中从嵌套列表中删除多个项?

pycoderr • 6 年前 • 1636 次点击  

如何在不使用列表理解的情况下从python 3的嵌套列表中删除多个项?有时 Indexerror 是怎么处理的?

split_list =[["a","b","c"],["SUB","d","e",],["f","Billing"]]
rem_word = ['SUB', 'Billing', 'Independent', 'DR']
for sub_list in split_list:
  for sub_itm in sub_list:
    if sub_itm not in rem_word:
        print(sub_itm)

输出如下:

 a
 b
 c
 d
 e
 f

预期产量:

split_list =[["a","b","c"],["d","e",],["f"]]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48395
文章 [ 3 ]  |  最新文章 6 年前
dataguy
Reply   •   1 楼
dataguy    6 年前

[[x代表x在z如果x!='sub']对于分割列表中的z]

请记住,它是一个嵌套列表将x作为子元素,将z作为元素还要记住,上面的代码将删除所有“SUB”仅用于删除第一个实例使用remove。

chris p bacon
Reply   •   2 楼
chris p bacon    6 年前

你可以简单地使用map和filter

split_list = [["a", "b", "c"], ["SUB", "d", "e", ], ["f", "Billing"]]
remove_list = ["SUB", "Billing", "INDEPENDENT", "DR"]
split_list = list(map(lambda x: list(filter(lambda i: i not in remove_list, x)), split_list))

print(split_list)
Arkistarvh Kltzuonstev
Reply   •   3 楼
Arkistarvh Kltzuonstev    6 年前

你可以使用总是使用列表理解在单独的列表中删除所有要删除的单词,然后尝试以下操作:

>>> split_list =[["a","b","c"],["SUB","d","e",],["f","Billing"]]
>>> rem_word = ['SUB', 'Billing', 'Independent', 'DR']
>>> output = [[sub_itm for sub_itm in sub_list if sub_itm not in rem_word] for sub_list in split_list]
[['a', 'b', 'c'], ['d', 'e'], ['f']]

如果要在不理解列表的情况下执行此操作,则需要声明一个空列表以附加每个新的子列表,还需要声明一个新的空子列表以附加所有新的子项。检查这个:

output2 = []
for sub_list in split_list:
    new_sub_list = []
    for sub_itm in sub_list:
        if sub_itm not in rem_word:
            new_sub_list.append(sub_itm)
    output2.append(new_sub_list)

输出相同:

[['a', 'b', 'c'], ['d', 'e'], ['f']]