Skip to content Skip to sidebar Skip to footer

Custom Sort A List By Fixing The First Element

I have a list [25, 35, 54, 70, 68, 158, 78, 11, 18, 12] I want to sort this list by fixing the first element i.e: if I fix 35 the sorted list should look like [35, 54, 68, 70, 78

Solution 1:

Just define a key function like:

Code:

defsorter(threshold):
    defkey_func(item):
        if item >= threshold:
            return0, item
        return1, item

    return key_func

This works by returning a tuple such that the numbers above threshold will sort below the numbers under the threshold.

Test Code:

data = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]
print(sorted(data, key=sorter(70)))

Results:

[70, 78, 158, 11, 12, 18, 25, 35, 54, 68]

Solution 2:

This will do the job

a = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]
a.sort()
index = a.index(35)
a = a[index:] + [:index]

print(a) #[35, 54, 68, 70, 78, 158, 11, 12, 18, 25]

Solution 3:

You can sort the list and then recover the index of the element with lst.index to pivot it.

Code

def pivot_sort(lst, first_element):
    lst = sorted(lst)
    index = lst.index(first_element)

    return lst[index:] + lst[:index]

Example

lst = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]

print(pivot_sort(lst , 70))
# prints: [70, 78, 158, 11, 12, 18, 25, 35, 54, 68]

Solution 4:

A fast and simple numpy solution:

def numpy_roll(arr, elem):
    arr = np.sort(arr)
    return np.roll(arr, len(arr)-np.argwhere(arr==elem)[0])

x
# array([17, 30, 16, 78, 54, 83, 92, 16, 73, 47])

numpy_roll(x, 16)
# array([16, 16, 17, 30, 47, 54, 73, 78, 83, 92])

Solution 5:

Combined use of itertools.cycle and itertools.islice.

Code:

from itertools import cycle, islice

def pivot_sort(lst, pivot):
    sorted_lst = sorted(lst)
    return list(islice(cycle(sorted_lst), sorted_lst.index(pivot), 2*len(sorted_lst)-lst.index(pivot)))


lst = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]
pivot = 70print(pivot_sort(lst, pivot))

# [70, 78, 158, 11, 12, 18, 25, 35, 54, 68]

Post a Comment for "Custom Sort A List By Fixing The First Element"