I am trying to sort the keys_list by removing items that don't appear in a list that is already sorted how I want it (sorted_category_list).
sorted_category_list = ['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'Master Men', 'Master Women', 'U21 Men', 'U21 Women',
'U17 Men', 'U17 Women', 'U17 Men', 'U17 Women', 'U15 Mixed', 'Hardtail', 'E-Bike']
keys_list = ['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'U15 Mixed', 'U17 Men', 'U21 Men', 'U21 Women']
for category in sorted_category_list:
if category not in keys_list:
sorted_category_list.remove(category)
print(sorted_category_list)
print(keys_list)
How ever I only get this results. It seems to remove some items but not others so I'm not sure what I am doing wrong:
['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'Master Women', 'U21 Men', 'U21 Women', 'U17 Men', 'U17 Men', 'U15 Mixed', 'E-Bike']
['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'U15 Mixed', 'U17 Men', 'U21 Men', 'U21 Women']
CodePudding user response:
This is because list.remove()
removes only the first element that is found hence if you have two same elements in the list it removes only one.
sorted_category_list = ['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'Master Men', 'Master Women', 'U21 Men', 'U21 Women',
'U17 Men', 'U17 Women', 'U17 Men', 'U17 Women', 'U15 Mixed', 'Hardtail', 'E-Bike']
keys_list = ['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'U15 Mixed', 'U17 Men', 'U21 Men', 'U21 Women']
sorted_category_list = [a for a in sorted_category_list if a in keys_list]
print(sorted_category_list)
print(keys_list)
CodePudding user response:
Convert the keys into a set:
keys_list = {'Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'U15 Mixed', 'U17 Men', 'U21 Men', 'U21 Women'}
Then remove using the set:
sorted_category_list = ['Elite Men', 'Elite Women', 'Open Men', 'Open Women', 'Master Men', 'Master Women', 'U21 Men', 'U21 Women',
'U17 Men', 'U17 Women', 'U17 Men', 'U17 Women', 'U15 Mixed', 'Hardtail', 'E-Bike']
sorted_category_list[:] = [i for i in sorted_category_list if i in keys_list]
CodePudding user response:
I would recommend maybe just appended the items in both lists to a new list. This way you can avoid altering your original list.
repeats=[]
for item in keys_list:
if item in sorted_category_list:
repeats.append(item)
CodePudding user response:
The issue is you are iterating and modifying a list at the same time.
Consider a list ['a','b','c','d']
and you have a code
for char in list:
if char == 'a':
list.remove(char)
In this case how the list is being iterated is
Loop 1 : char = a (Index 0)
Since char is removed the index that is going to be searched next is 1.
But the list now is ['b','c','d']
so the char at index at 1 is 'c' so 'b' gets skipped.
So in your case the first element getting deleted is 'Master Men' so the next element i.e. 'Master Women' gets skipped which is why it is in the list and with every deletion the next element gets skipped.