简体   繁体   中英

How to remove sublist from a list based on indices in another list?

I have these lists:

ls = [[0, "a"],
      [2, "c"]]

ls2 = [[0, "a"],
       [1, "b"],
       [2, "c"],
       [3, "d"],
       [4, "e"]]

I want to remove all sublists from ls2 that are not in ls . So at the end ls2 should be the same as ls . I tried this:

ls = [[0, "a"],
      [2, "c"]]

ls2 = [[0, "a"],
       [1, "b"],
       [2, "c"],
       [3, "d"],
       [4, "e"]]

indices_left = [l[0] for l in ls]

for subll in ls2:
    if subll[0] not in indices_left:
        ls2.pop(subll[0])

for subll2 in ls2:
    print(subll2)

But this gives:

[0, 'a']
[2, 'c']
[3, 'd']

I think this is because the first for loop removes list [1, "b"] but after that list [2, "c"] moves to ls2[1] and list [3, "d"] moves to ls2[2] and since ls[1][0] == 2 , sublist [3, "d"] is not removed because it is now at index ls2[2] . How can I avoid this and remove all sublists from ls2 that are not in ls ?

Ignoring the fact that there's no use for your code because if you want ls2 to be identical to ls you could just copy it, the following list comprehension will work:

ls = [[0, "a"],
      [2, "c"]]

ls2 = [[0, "a"],
       [1, "b"],
       [2, "c"],
       [3, "d"],
       [4, "e"]]
ls2 = [x for x in ls2 if x in ls]

Edit

If the goal is to select only elements from ls2 that have the same first element as an item from ls , then this will work:

indices = [x[0] for x in ls]
ls2 = [x for x in ls2 if x[0] in indices]

List comprehension.

ls = [[0, "a"],
      [2, "c"]]

ls2 = [[0, "a"],
       [1, "b"],
       [2, "c"],
       [3, "d"],
       [4, "e"]]
ls2 = [x for x in ls2 if x in ls]

        

print(ls2)

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