这可能很简单,但我无法理解它。
我有一个列表,例如:
list_a = [['Peter', '2016'],['David', '2020'],['Ulrik', '2018'],['Lars', '2017'],['Dave', '2019'],['Ann', '2015']]
然后用户可以选择一些项目,比如 ['Peter', '2016']
和 ['Lars', '2017']
。然后将选择存储为索引,如:
user_selection = [0,3]
现在,我希望对 list_a
进行排序:
list_a.sort(key=itemgetter(1), reverse=False)
该列表现在按日期排序,如下所示:
list_a = [['Ann', '2015'], ['Peter', '2016'], ['Lars', '2017'], ['Ulrik', '2018'], ['Dave', '2019'],['David', '2020']]
但是,正如您从我的标题中猜到的,user_selection
现在是“错误的”,指的是用户没有选择的项目。我如何“更新”选择(或将其与列表一起排序)使其变为:
user_selection = [1,2]
?
答案 0 :(得分:1)
重做我的答案:
这里有一个完整的例子:
list_a = [['Peter', '2016'],['David', '2020'],['Ulrik', '2018'],['Lars', '2017'],['Dave', '2019'],['Ann', '2015']]
这是您的清单。
如果 user_selection
现在关注:
user_selection = [0,3]
您可以执行以下操作:
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.
然后就可以了。没试过,但逻辑应该可行。
或者简单的方法。
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)
我希望你现在可以理解它。