简体   繁体   中英

Remove a tuple from a list if the tuple contains a certain element by given index

I have a list of tuples (num, id):

l = [(1000, 1), (2000, 2), (5000, 3)]

The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of 2 , how do I do that?

Ie I want the new list to be: l = [(1000,1), (5000, 3)]

I have tried l.remove(2) but it won't work.

You can use a list comprehension with a filter to achieve this.

l = [(1000, 1), (2000, 2), (5000, 3)]
m = [(val, key) for (val, key) in l if key != 2]

That's because the value 2 is not in the list. Instead, something like the below: form a list of the second elements in your tuples, then remove the element at that position.

del_pos = [x[1] for x in l].index(2)
l.pop(del_pos)

Note that this removes only the first such element. If your instance is not unique, then use one of the other solutions. I believe that this is faster, but handles only the single-appearance case.

Or using filter:

l = [(1000, 1), (2000, 2), (5000, 3)]
print(list(filter(lambda x: x[1] != 2, l)))

output:

[(1000, 1), (5000, 3)]

You may do it with:

>>> l = [(1000, 1), (2000, 2), (5000, 3)]
>>> for i in list(l):
...     if i[1] == 2:
...         l.remove(i)

In case you want to remove only first occurence, add break below remove line

简单的列表理解:

[x for x in l if x[1] != 2]

One more possible solution

r = [(1000, 1), (2000, 2), (5000, 3)]
t = [i for i in r if i.count(2) == 0]

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