how to remove an element from a nested list?

后端 未结 8 1156
一生所求
一生所求 2020-12-17 00:37

if i have an nested list such as:

m=[[34,345,232],[23,343,342]]

if i write m.remove(345) it gives an error message saying elem

相关标签:
8条回答
  • 2020-12-17 00:56

    You can delete by using delete:- del m[1][1] or by using below code

    for i in m:
        for j in i:
            if j==345:
                i.remove(j)
    print(m)
    
    0 讨论(0)
  • 2020-12-17 00:56

    A shortcut of doing this is using del command:

    del list[element] element[nested element] 
    
    del [] []
    
    0 讨论(0)
  • 2020-12-17 00:58

    There is no shortcut for this. You have to remove the value from every nested list in the container list:

    for L in m:
        try:
            L.remove(345)
        except ValueError:
            pass
    

    If you want similiar behavior like list.remove, use something like the following:

    def remove_nested(L, x):
        for S in L:
            try:
                S.remove(x)
            except ValueError:
                pass
            else:
                break  # Value was found and removed
        else:
            raise ValueError("remove_nested(L, x): x not in nested list")
    
    0 讨论(0)
  • 2020-12-17 01:05

    You can remove 345 by using this code.

    m[0].remove(345)
    
    0 讨论(0)
  • 2020-12-17 01:07

    If you have more than one nested level this could help

    def nested_remove(L, x):
        if x in L:
            L.remove(x)
        else:
            for element in L:
                if type(element) is list:
                    nested_remove(element, x)
    
    >>> m=[[34,345,232],[23,343,342]]
    >>> nested_remove(m, 345)
    >>> m
    [[34, 232], [23, 343, 342]]
    
    >>> m=[[34,[345,56,78],232],[23,343,342]]
    >>> nested_remove(m, 345)
    >>> m
    [[34, [56, 78], 232], [23, 343, 342]]
    
    0 讨论(0)
  • 2020-12-17 01:10

    If you want to remove only by indexes you can use this method

    m[0].pop(1)
    

    by this you can specify only the index. This is helpful if you know only the position you want to remove.

    0 讨论(0)
提交回复
热议问题