首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在排序列表后保留选择/获取新索引?

如何在排序列表后保留选择/获取新索引?
EN

Stack Overflow用户
提问于 2021-01-25 18:11:12
回答 1查看 52关注 0票数 0

这可能很简单,但我无法理解它。

我有一个这样的列表:

代码语言:javascript
复制
list_a = [['Peter', '2016'],['David', '2020'],['Ulrik', '2018'],['Lars', '2017'],['Dave', '2019'],['Ann', '2015']]

然后,用户可以选择一些项目,比如['Peter', '2016']['Lars', '2017']。然后将选择存储为索引,如下所示:

代码语言:javascript
复制
user_selection = [0,3]

现在,我希望对list_a进行如下排序:

代码语言:javascript
复制
list_a.sort(key=itemgetter(1), reverse=False)

该列表现在按日期排序,如下所示:

代码语言:javascript
复制
list_a = [['Ann', '2015'], ['Peter', '2016'], ['Lars', '2017'], ['Ulrik', '2018'], ['Dave', '2019'],['David', '2020']]

然而,正如你已经从我的标题中猜到的那样,user_selection现在是“错误的”,它引用了用户没有选择的项目。如何“更新”选定内容(或将其与列表一起排序),使其变为:user_selection = [1,2]

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-25 18:16:49

修改我的答案:

下面是一个完整的示例:

代码语言:javascript
复制
list_a = [['Peter', '2016'],['David', '2020'],['Ulrik', '2018'],['Lars', '2017'],['Dave', '2019'],['Ann', '2015']]

这是你的单子。

如果user_selection现在如下所示:

代码语言:javascript
复制
user_selection = [0,3]

您可以执行以下操作:

代码语言:javascript
复制
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.

这就对了,它应该可以工作。我还没有尝试过,但是逻辑应该是有效的。

或者是简单的方式。

代码语言:javascript
复制
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)

我希望你现在可以理解了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65882680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档