对列表进行排序并在未排序的列表中获取索引 [英] sorting list of lists and getting indices in unsorted list

查看:108
本文介绍了对列表进行排序并在未排序的列表中获取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我需要在列表列表中执行的逻辑步骤

These are the logical steps that I need to perform on my list of lists

a = [[5,2],[7,4],[0,3]]

  1. 对列表列表进行排序,使输出看起来像

  1. sort the list of lists in such a way that the output looks something like

7,5,4,3,2,0

  • 获取原始列表中已排序元素的坐标,在这种情况下应将其作为输出

  • take the coordinates of the sorted elements in the original list, which in this case should produce as output

    (1,0)
    (0,0)
    (1,1)
    (2,1)
    (0,1)
    (2,0)
    

  • 我尝试以不同的方式使用sort, sortedargwhere,但是我没有得到合理的结果,我想首先是因为sortsorted一次只能沿一个轴对列表进行排序

    I tried using of sort, sorted and argwhere in different ways but I am not getting sensible results, I guess first of all because sort and sorted can sort a list following only one axis at a time

    推荐答案

    此代码适用于列表列表.内部列表的长度不必相同.

    This code will work for a list of lists. The internal lists don't have to be the same length.

    在每个级别,我们使用enumerate遍历列表以获取列表项及其索引.在顶层,每个项目都是另一个列表,并且内部循环遍历每个列表以获取其索引和值,并将索引(作为元组)存储在也包含值的元组中.然后,我们对所得的元组(b)列表进行排序,然后使用zip将其拆分为所有索引的元组和值的元组.

    At each level we iterate over a list using enumerate to get the list item and its index. At the top level, each item is another list, and the inner loop iterates over each of those lists to get their indices and values, storing the indices (as a tuple) in a tuple that also contains the value. We then sort the resulting list of tuples (b) on the values, and then split it using zip into a tuple of all the indices and a tuple of the values.

    from operator import itemgetter
    
    a = [[5, 2], [7, 4], [0, 3]]
    
    b = [((i, j), v) for i, t in enumerate(a) for j, v in enumerate(t)]
    b.sort(key=itemgetter(-1), reverse=True)
    print(b)
    coords, vals = zip(*b)
    print(vals)
    print(coords)
    

    输出

    [((1, 0), 7), ((0, 0), 5), ((1, 1), 4), ((2, 1), 3), ((0, 1), 2), ((2, 0), 0)]
    (7, 5, 4, 3, 2, 0)
    ((1, 0), (0, 0), (1, 1), (2, 1), (0, 1), (2, 0))
    

    这篇关于对列表进行排序并在未排序的列表中获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆