how to remove an element from a nested list?

后端 未结 8 1157
一生所求
一生所求 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 01:20
    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.

    0 讨论(0)
  • 2020-12-17 01:21
    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.

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