简体   繁体   中英

How to remove an element from a nested list?

if I have a nested list such as:

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

if I write m.remove(345) it gives an error message saying the element is not in the list.

I want to know how to remove an element from the nested list, easily.

In [5]: m=[[34,345,232],[23,343,342]]

In [7]: [[ subelt for subelt in elt if subelt != 345 ] for elt in m] 
Out[7]: [[34, 232], [23, 343, 342]]

Note that remove(345) only removes the first occurrance of of 345 (if it exists). The above code removes all occurrances of 345.

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")

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]]
i=0
for item in nodes:
    for itm in item:
        m=database_index[itm]
        print m
        if m[1]=='text0526' or m[1]=='text0194' or m[1]=='phone0526' or m[1]=='phone0194':
            nodes[i].remove(itm)
    i+=1

this i how i solved my problem by using a variable i to save the above level of the nested list.

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.

您可以使用此代码删除 345。

m[0].remove(345)

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)

A shortcut of doing this is using del command:

del list[element] element[nested element] 

del [] []

If you have the same item (ie 345) in more places to remove from the nested list, you can try:

for x in m:
    for index in range(len(x) -1, -1, -1):
        if x[index] == 345:
            del x[index]
    print(x)

or

for x in m:
    for z in x:
        if z != 345:
            print(z)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM