这可能很简单,但我无法理解它。
我有一个这样的列表:
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]?
发布于 2021-01-25 18:16:49
修改我的答案:
下面是一个完整的示例:
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)我希望你现在可以理解了。
https://stackoverflow.com/questions/65882680
复制相似问题