简体   繁体   中英

How do I delete a tuple in a list based on a value in the tuple?

I have a list of tuples. I want to remove all items in the list where the 2nd and 3rd items in the tuple are bananas and 1 . A for loop doesn't work since it's removing items from the list as it iterates through it. Not sure how else to go about this?

my_table = [('apples', 'bananas', 1), ('pears', 'bananas', 1), ('grapes', 'apple', 2), ('apples,' 'pears', 2), ('apples', 'bananas', 2), ('grapes', 'bananas', 2)]

>>> printTable(my_table)
('apples', 'bananas', 1)
('pears', 'bananas', 1)
('grapes', 'apple', 2)
('apples,pears', 2)
('apples', 'bananas', 2)
('grapes', 'bananas', 2)

>>> for item, row in enumerate(my_table):
    if row[1] == 'bananas' and row[2] == 1:
        print item, row

0 ('pears', 'bananas', 1)
5 ('apples', 'bananas', 1)
6 ('grapes', 'bananas', 1)

>>> for item, row in enumerate(my_table):
    if row[1] == 'bananas' and row[2] == 1:
        my_table.remove(row)

>>> printTable(my_table)
('pears', 'bananas', 1)
('grapes', 'apple', 2)
('apples,pears', 2)
('apples', 'bananas', 2)

Use a list comprehension instead:

my_table = [elem for elem in my_table if elem[1:] != ('bananas', 1)]

This looks at deletion as a filtering job; keep everything that should not be deleted by creating a new list instead.

您也可以:

filterted_table=filter(lambda t: t[1:]!=('bananas', 1),my_table)

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