Removing an item from a list of lists based on each of the lists first element

后端 未结 4 2006
鱼传尺愫
鱼传尺愫 2020-12-03 23:44

Given:

a = [[1,2],[3,4],[5,6],[7,8]]
b = 3

I would like to remove an item of a that has b as it\'s first item. S

相关标签:
4条回答
  • 2020-12-04 00:02
    for i in a[:-1]:
        if i[0]==b:
            a.remove(i)
    

    What about this?

    The output is

    [[1, 2], [5, 6], [7, 8]]

    0 讨论(0)
  • 2020-12-04 00:08

    You can use a list comprehension:

    >>> a = [[1,2],[3,4],[5,6],[7,8]]
    >>> b = 3
    >>> a = [x for x in a if x[0] != b]
    >>> a
    [[1, 2], [5, 6], [7, 8]]
    
    0 讨论(0)
  • 2020-12-04 00:16

    If your list are small then you are also try filter ,

    a = [[1,2],[3,4],[5,6],[7,8]]
    b = 3
    
    print(list(filter(lambda x:x[0]!=b,a)))
    

    output:

    [[1, 2], [5, 6], [7, 8]]
    
    0 讨论(0)
  • 2020-12-04 00:20

    Reverse delete a, modifying it in-place:

    for i in reversed(range(len(a))):
        if a[i][0] == 3:
            del a[i]
    

    An in-place modification means that this is more efficient, since it does not create a new list (as a list comprehension would).


    Since OP requests a performant solution, here's a timeit comparison between the two top voted answers here.

    Setup -

    a = np.random.choice(4, (100000, 2)).tolist()
    
    print(a[:5])
    [[2, 1], [2, 2], [3, 2], [3, 3], [3, 1]]
    

    List comprehension -

    %timeit [x for x in a if x[0] != b]
    11.1 ms ± 685 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    Reverse delete -

    %%timeit
    for i in reversed(range(len(a))):
        if a[i][0] == 3:
            del a[i]
    
    10.1 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    They're really close, but reverse delete has a 1UP on performance because it doesn't have to generate a new list in memory, as the list comprehension would.

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