简体   繁体   中英

Efficient way to find index of elements in a large list of integers starting with max to min elements

I have a large list of integers unsorted , numbers might be duplicated. I would like to create another list which is a list of sub-lists of indexes from the first list starting with max element to min, in decreasing order. For example, if I have a list like this:

list = [4, 1, 4, 8, 5, 13, 2, 4, 3, 7, 14, 4, 4, 9, 12, 1, 6, 14, 10, 8, 6, 4, 11, 1, 2, 11, 3, 9]

The output should be:

indexList = [[10, 17], [5], [14], [22, 25], [18], [13, 27], [3, 19], [9], [16, 20], [4], [0, 2, 7, 11, 12, 21], [8, 26], [6, 24], [1, 15, 23]]

where, [10, 17] is the index of where ' 14 ' is present and so on...

Shared my code below. Profiling it using cProfile for a list of around 9000 elements takes around ~6 seconds.

def indexList(list):
    # List with sorted elements
    sortedList = sorted(list, reverse = True)

    seen = set()
    uSortedList = [x for x in sortedList if x not in seen and not seen.add(x)]

    indexList = []
    for e in uSortedList:
        indexList.append([i for i, j in enumerate(list) if j == e])

    return indexList

Here you go:

def get_list_indices(ls):
    indices = {}
    for n, i in enumerate(ls):
        try:
            indices[i].append(n)
        except KeyError:
            indices[i] = [n]
    return [i[1] for i in sorted(indices.items(), reverse=True)]

test_list = [4, 1, 4, 8, 5, 13, 2, 4, 3, 7, 14, 4, 4, 9, 12, 1, 6, 14, 10, 8, 6, 4, 11, 1, 2, 11, 3, 9]
print(get_list_indices(test_list))

Based on some very basic testing, it is about twice as fast as the code you posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM