Reputation: 340
This might be simple, but I'm unable to wrap my head around it.
I have a list such as:
list_a = [['Peter', '2016'],['David', '2020'],['Ulrik', '2018'],['Lars', '2017'],['Dave', '2019'],['Ann', '2015']]
A user is then able to select some items, lets say ['Peter', '2016']
and ['Lars', '2017']
. The selection is then stored as indexes like:
user_selection = [0,3]
Now, i wish to sort list_a
like:
list_a.sort(key=itemgetter(1), reverse=False)
The list is now ordered by date and looks like:
list_a = [['Ann', '2015'], ['Peter', '2016'], ['Lars', '2017'], ['Ulrik', '2018'], ['Dave', '2019'],['David', '2020']]
However, as you've guessed from my title, user_selection
is now "wrong" and refers to items the user did not select. How do i "update" the selection (or sort it along with the list) so it becomes:
user_selection = [1,2]
?
Upvotes: 0
Views: 61
Reputation: 363
Rework of my answer:
Here a full example:
list_a = [['Peter', '2016'],['David', '2020'],['Ulrik', '2018'],['Lars', '2017'],['Dave', '2019'],['Ann', '2015']]
this is your list.
If user_selection
is now following:
user_selection = [0,3]
You could do following:
user_selected_lists = [] # a list where we safe the inputs from list_a which the user selected
for selected in user_selection:
user_selected_lists.append(list_a[selected]) # this takes the item at the index the user selected and safes it into the `user_selected_lists`
# Now you have the both lists the user selected in the `user_selected_lists`
new_indexes = [] # the new indexes of the selected lists
for selected_list in user_selected_lists:
new_indexes.append(list_a.index(selected)) # this gets the new index from the new list of each list we safed from the first list.
And there you go it should work. Haven't tried it but the logic should work.
Or the simple way.
list_a_duplicate = list_a # make a duplicate from list_a
list_a.sort() # sort the list as you wish
# If you want now to know what index 0 and 3 are NOW after sorting you can just do following.
old_indexes_now = [] # the new indexes
for index in user_selection:
list_item = list_a_duplicate[index] # get each item of the old list
new_index = list_a.index(list_item) # get the index of the item from the new list
old_indexes_now.append(new_index)
I hope its understandable for you now.
Upvotes: 1