Python_newbie
Python_newbie

Reputation: 203

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, 158, 11, 12, 18, 25]

If I fix 158 as the first element the sorted list should look like

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

basically I want to fix the first element and the rest should be in sorted order, if there is a number that is lesser than the first element is found it should not go before first element. Is there a builtin function available for this in Python?

Upvotes: 3

Views: 655

Answers (5)

Austin
Austin

Reputation: 26039

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 = 70

print(pivot_sort(lst, pivot))

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

Upvotes: 0

user3483203
user3483203

Reputation: 51165

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])

Upvotes: 0

Olivier Melançon
Olivier Melançon

Reputation: 22314

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]

Upvotes: 0

Stephen Rauch
Stephen Rauch

Reputation: 49814

Just define a key function like:

Code:

def sorter(threshold):
    def key_func(item):
        if item >= threshold:
            return 0, item
        return 1, 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]

Upvotes: 3

rsanath
rsanath

Reputation: 1210

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]

Upvotes: 0

Related Questions