问题
I've been scratching my head for an hour on this issue. I'm trying to create a function that removes an item from a list of tuples is the tuple contains a 0 in position 1.
players = [('a', 1), ('b', 0), ('c', 1), ('d', 1), ('e', 1), ('f', 1),
('g', 0), ('h', 1), ('i', 1), ('j', 0), ('k', 0), ('l', 1)]
def splittuple(mylist):
for counter, i in enumerate(mylist):
print counter, 'original: '+ str(i)
if i[1] == 0:
players.remove(i)
print players
It prints the following output:
0 original: ('a', 1)
1 original: ('b', 0)
2 original: ('d', 1)
3 original: ('e', 1)
4 original: ('f', 1)
5 original: ('g', 0)
6 original: ('i', 1)
7 original: ('j', 0)
8 original: ('l', 1)
[('a', 1), ('c', 1), ('d', 1), ('e', 1), ('f', 1), ('h', 1), ('i', 1), ('k', 0), ('l', 1)]
I'm not sure why the ('k', 0) tuple remains on the list. It's i[1] value is equal to 0, but it looks like the for loop is skipping over it. I was expecting it to be removed.
It looks like the loop gets confused if the user passes two tuples with 0 in position 1 in a row.
来源:https://stackoverflow.com/questions/43152898/list-remove-skipping-an-item-in-a-list