Home  >  Article  >  Backend Development  >  How to insert variables into a sorted array using Python in a fast way?

How to insert variables into a sorted array using Python in a fast way?

WBOY
WBOYforward
2023-05-09 22:49:201257browse

Using sort and sorted sorting

Modify and generate new variables in place

In the process of learning python, the quick sorting function of the list is a required course for us. To introduce a method of quickly inserting an ordered sequence, let's first look at the differences and connections between the two sorting functions. First let's look at sort(), please look at the following code:

import random
# 随机生成10个100以内的整数
example_list = [random.randint(1,100) for i in range(10)]
# 对他们进行排序
example_list.sort()
print(example_list)

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

It should be noted that the **sort()** function here does not have any return value , but perform in-place sorting, please see the following code:

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

>>> None

When we use a new variable to receive the sorted content, we find that we get None. But **sorted()** is just the opposite. It will generate a new variable to store the sorted list. Please see the following code:

import random
example_list = [random.randint(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, we use **sorted() **When sorting, a new variable storage is generated and obtained by us.

Commonly used parameters

Of course, the parameters used by the two sorting functions have a lot of the same content. Let’s look at the following example:

import random # 导入 random 模块,用于生成随机数

# 创建一个包含 10 个随机整数的列表,每个数的范围在 1 到 100 之间
example_list_argTest = [random.randint(1, 100) for i in range(10)]

# 将列表按升序排序并打印输出
example_list_argTest.sort()
print(example_list_argTest)

# 将列表按降序排序并打印输出
example_list_argTest.sort(reverse=True)
print(example_list_argTest)

# 创建一个包含三个子列表的列表
example_list_argTest_02 = [[5, 7], [1, 8], [9, 6]]
print(example_list_argTest_02)

# 对子列表按第一个元素排序并打印输出
example_list_argTest_02.sort()
print(example_list_argTest_02)

# 对子列表按第二个元素排序并打印输出
def takeSecond(test_list):
    return test_list[1]

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

# 创建一个包含四个字符串的列表
example_list_argTest_03 = ['apple', 'big apple', 'pear', 'hen']
print(example_list_argTest_03)

# 对字符串按长度排序并打印输出
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() **The function parameters are the same. The following are commonly used parameter values ​​and their meanings:

  • key: The parameter can accept a function as a parameter, which will be applied to the list. each element to sort. This function should accept one parameter and return the value to be used for sorting.

  • reverse: An optional parameter used to control the order in which the list is sorted. When reverse is True, the list is sorted in descending order; when reverse is False or not specified (the default is False), the list is sorted in ascending order.

Use bisect to insert variables into an ordered sequence

Get the position of the inserted element

bisect is used to insert elements in a sorted list, and Returns the index into the list after inserting the element. There are two available functions, namely bisect_left() and bisect_right(). Obviously the main difference is that one will return the index of the left insert, and the other will return the index of the right insert. index. Please look at the following example:

import bisect

example_list = [random.randint(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, the above two functions also have two optional parameters, which are as follows:

  • The lo parameter indicates the search range The starting position can be used to specify a search in a subrange of the list.

  • The hi parameter indicates the end position of the search range and can be used to specify a search in a subrange of the list.

We can use the above parameters to select part of the interval for insertion. Please see the following example:

test_list = list(range(10))
print(test_list)
# 指定区间搜索插入
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 search interval for insertion, And returns the inserted index position.

Use insort to insert elements into an ordered sequence

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

import bisect

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

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

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

An application example

Suppose we want to rate the input results. In fact, we can write it using the method introduced above. Please see the following example:

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

random_grades = [random.randint(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']

Passed Properly using the above function to insert the sequence, we completed a performance rating function and returned the ratings corresponding to different grades.

The above is the detailed content of How to insert variables into a sorted array using Python in a fast way?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete