我有一个元组列表。我想删除列表中元组中第 2 和第 3 项为bananas
and的所有项1
。for 循环不起作用,因为它在遍历列表时会从列表中删除项目。不知道该怎么做?
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)