SoFunction
Updated on 2024-11-15

Python Advanced - How to Quickly Insert Variables into an Ordered Array

Learning sequences is a mandatory part of our python learning process. Once we have mastered sequences, we learn the two commonly used sorting functionssort()together withsorted(). However, few introductory courses introduce two common functions for inserting arrays, so today we'll look together at how to quickly insert variables into ordered arrays.

Sorting with sorted

In-place modification and generation of new variables

Fast sorting functions for lists are a must as we learn python. Wanting to introduce fast insertion of ordered lists, we first look at the differences and connections between the two sorting functions. Let's first look atsort()Please see the code below:

import random
# Generate 10 random integers up to 100
example_list = [(1,100) for i in range(10)]
# Sort them out
example_list.sort()
print(example_list)

>>> [22, 28, 35, 47, 49, 55, 68, 79, 87, 98]

It's important to note that the **sort()** function here doesn't return any value, but instead sorts in place, see the code below:

import random
example_list = [(1,100) for i in range(10)]
example_list_sort_test = example_list.sort()
print(example_list_sort_test)

>>> None

When we utilize a new variable to receive the sorted contents, we find that we get None. but **sorted()** does the opposite, its generates a new variable to store the sorted list, see the code below:

import random
example_list = [(1,100) for i in range(10)]
example_list_sorted_test = sorted(example_list)
print(example_list_sorted_test)

>>> [6, 14, 14, 20, 28, 50, 58, 58, 71, 83]

As you can see, when we sorted using **sorted()**, new variables were generated to be stored and fetched by us.

Common Parameters

Of course, the two sort functions use many of the same parameters, as we see in the following example:

import random # Import the random module for generating random numbers

# Create a list of 10 random integers, each ranging from 1 to 100
example_list_argTest = [(1, 100) for i in range(10)]

# Sort the list in ascending order and print out the output
example_list_argTest.sort()
print(example_list_argTest)

# Sort the list in descending order and print out the output
example_list_argTest.sort(reverse=True)
print(example_list_argTest)

# Create a list with three sublists
example_list_argTest_02 = [[5, 7], [1, 8], [9, 6]]
print(example_list_argTest_02)

# Sort the sub-list by the first element and print the output
example_list_argTest_02.sort()
print(example_list_argTest_02)

# Sort the sub-list by the second element and print the output
def takeSecond(test_list):
    return test_list[1]

example_list_argTest_02.sort(key=takeSecond)
print(example_list_argTest_02)

# Create a list of four strings
example_list_argTest_03 = ['apple', 'big apple', 'pear', 'hen']
print(example_list_argTest_03)

# Sort the string by length and print out the output
example_list_argTest_03.sort(key=len)
print(example_list_argTest_03)

>>>[4, 18, 26, 41, 43, 52, 77, 77, 97, 98]
>>>[98, 97, 77, 77, 52, 43, 41, 26, 18, 4]
>>>[[5, 7], [1, 8], [9, 6]]
>>>[[1, 8], [5, 7], [9, 6]]
>>>[[9, 6], [5, 7], [1, 8]]
>>>['apple', 'big apple', 'pear', 'hen']
>>>['hen', 'pear', 'apple', 'big apple']

Among them, **sorted()** function parameters with its is the same, the following is commonly used parameter values and the meaning of the parameters:

  • The key: parameter can accept as an argument a function that will be applied to each element in the list to be sorted. The function should take one argument and return the value to be used for sorting.
  • reverse: an optional parameter to control the order in which the list is sorted. When reverse is True, the list will be sorted in descending order; when reverse is False or unspecified (default is False), the list will be sorted in ascending order.

Inserting variables into an ordered sequence using bisect

Get the position of the inserted element

bisect is used to insert elements into a sorted list and return the index of the list after inserting the elements. There are two functions available in it, namelybisect_left() cap (a poem)bisect_right()The main difference, obviously, is that one returns the index to the left of the insertion, and one returns the index to the right of the insertion. See the following example:

import bisect

example_list = [(1,100) for i in range(10)]
example_list.sort()
print(example_list)

left_index = bisect.bisect_left(example_list_sorted_test,58)
print(left_index)

right_index = bisect.bisect_right(example_list_sorted_test,58)
print(right_index)

>>>[9, 11, 16, 22, 40, 59, 60, 68, 83, 99]
>>>6
>>>8

In addition to this, the above two functions have two optional parameters, which are as follows:

  • The lo parameter indicates the starting position of the search range and can be used to specify that the search is to be performed in a subinterval of the list.
  • The hi parameter indicates the end position of the search range and can be used to specify that the search is to be performed in a subinterval of the list.

We can use the above parameters to select part of the interval for insertion, see the example below:

test_list = list(range(10))
print(test_list)
# Specified interval search insertion
bisect.bisect_left(test_list, 2, 3, 5)

>>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>3

In this example, we specify the interval insertion for the search and return the index position of the insertion.

Inserting elements into an ordered sequence using insort

If you want to insert elements into a list without destroying its sort order, you can use the **insort()** function. Consider the following simple example:

import bisect

sorted_list_example = [1, 3, 4, 6, 8, 9, 11]
(sorted_list_example, 7)
print(sorted_list_example )

>>> [1, 3, 4, 6, 7, 8, 9, 11]

In the above example, we inserted custom variables into the ordered array.

An example of an application

Suppose we want to grade the input grades, which can actually be written in the way described above, see the following example:

def grade(score, breakpoints = [60,70,80,90], grades='FDCBA'):
    index = (breakpoints, score)
    return grades[index]

random_grades = [(1,100) for i in range(10)]
print(random_grades)

print([grade(s) for s in random_grades])

>>>[27, 28, 35, 89, 20, 61, 20, 89, 53, 92]
>>>['F', 'F', 'F', 'B', 'F', 'D', 'F', 'B', 'F', 'A']

By rationalizing the use of the above function for inserting sequences, we have completed a function for rating grades and returned the ratings corresponding to different grades.

summarize

In this article, we covered list sorting and how to quickly insert a list sequence using python's built-in functions.

This article on Python advanced how to quickly insert variables into an ordered array of articles on this, more related Python variables into an ordered array of content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!