Home > Backend Development > Python Tutorial > How to get a sorted list of random integers with unique elements using Python?

How to get a sorted list of random integers with unique elements using Python?

WBOY
Release: 2023-08-21 20:28:32
forward
1581 people have browsed it

How to get a sorted list of random integers with unique elements using Python?

Generating random numbers is one of the most popular techniques in programming, statistics, machine learning models, and more. Generating a sorted list of random integers with unique elements is a subfield of this task. However, computers are deterministic machines, so generating random numbers through our implementation is only sometimes a sensible idea. In this article, we will explore how to get a sorted list of random integers with unique elements using Python.

Example function using random module

The sampling method generates a random sample of k elements from a given population. It takes two required parameters, the first is the list of elements and the second is the number of elements that should be included in our sample list.

grammar

random.sample(iterable object, k)
Copy after login

The function sample accepts two required parameters: an iterable object and the number of elements that should be present in the result. It returns the k elements in the iterable object as a list.

sorted(iterable, key=< value of the key > , reverse = <boolean True or False> )
Copy after login

This function sorts iterable objects. It takes an iterable object as a required parameter. We can also set the key of an element using the key parameter. We can also use the reverse parameter to return the reverse form of the sorted iterable.

The Chinese translation of

Example

is:

Example

In the following code, we first import Python’s random module. Next, we created the generate_sorted_random_integers function, which accepts three parameters, the starting range, the ending range, and the number of elements. We create a list of integer ranges using the range method, take some samples from it using the sample method, and finally sort the array using the sorted method.

import random
def generate_sorted_random_integers(start_range, end_range, num_elements):
    random_list = sorted(random.sample(range(start_range, end_range + 1), num_elements))
    return random_list
start_range = 1
end_range = 100
num_elements = 10
random_list = generate_sorted_random_integers(start_range, end_range, num_elements)
print(f"The sorted list of random integers is: {random_list}")

Copy after login

Output

The sorted list of random integers is: [6, 18, 19, 55, 63, 75, 88, 91, 92, 94]
Copy after login

Using Numpy module

Numpy is a popular library for Python used for numerical calculations. It also provides functions for creating random numbers. We can use the sort method to sort the list and the choice method to randomly select k elements.

grammar

numpy.choice(<array name>, size=<shape of the output array> , replace=
<Boolean True or False>, other parameters....)
Copy after login

The Chinese translation of

Example

is:

Example

In the following example, after importing the Numpy library, we define the generate_sorted_random_integers function. This function takes a start value, an end value, and the number of elements as parameters and returns a randomly ordered list. Below the function, we use the range function to generate a sequence, the choice method to select the required number of elements from it, and finally the sort method to sort the list.

import numpy as np
def generate_sorted_random_integers(start_range, end_range, num_elements):
    random_list = np.sort(np.random.choice(range(start_range, end_range + 1), size=num_elements, replace=False))
    return random_list
start_range = 10
end_range = 100
num_elements = 10
random_list = generate_sorted_random_integers(start_range, end_range, num_elements)
print(f"The sorted list of random integers is: {random_list}")
Copy after login

Output

The sorted list of random integers is: [23 27 61 72 74 79 80 90 96 99]
Copy after login

Using list comprehensions and sorting

List comprehensions are a popular technique among Python developers. The advantage of this approach is that you can combine logical statements, iteration expressions, conditional expressions, etc. in a single line of code and generate the elements of a list based on it. This helps in writing a single derivation of a line of code.

The Chinese translation of

Example

is:

Example

In the following example, we use list comprehension to create a sorted list of random numbers. We use Python's random library to create random numbers in the desired range and use the sorted method to sort the list of random numbers. We called the user-defined function, passed the necessary parameters, and printed the result.

import random
def generate_sorted_random_integers(start_range, end_range, num_elements):
    random_list = sorted([random.randint(start_range, end_range) for _ in range(num_elements)])
    return random_list
start_range = 10
end_range = 50
num_elements = 10
random_list = generate_sorted_random_integers(start_range, end_range, num_elements)
print(f"The sorted list of random integers is: {random_list}")

Copy after login

Output

The sorted list of random integers is: [12, 13, 15, 16, 16, 25, 28, 29, 47, 49]
Copy after login

Use Lambda function

Lambda functions do not have any name and they behave like traditional functions if there are fewer lines of code. This function can accept parameters and return a value. However, the function does not have any name. Typically, we use functions like this when we need to perform some operations quickly and are confident that they won't be used elsewhere.

The Chinese translation of

Example

is:

Example

In the code below, we use the lambda function, which takes start, end and number of elements as parameters. This function also uses list comprehensions to generate the elements of the list. We use the randint method to generate random numbers and the sorted method to sort the list.

import random
generate_sorted_random_integers = lambda start_range, end_range, num_elements: sorted([random.randint(start_range, end_range) for _ in range(num_elements)])
start_range = 1
end_range = 100
num_elements = 10
random_list = generate_sorted_random_integers(start_range, end_range, num_elements)
print(f"The sorted list of random integers is: {random_list}")
Copy after login

Output

The sorted list of random integers is: [7, 14, 32, 46, 55, 68, 79, 84, 88, 90]
Copy after login

Use Lambda function

Pandas is a popular data analysis library in Python. It has a built-in function called apply, which we can use to apply certain operations to all list elements. We can use the random library to generate random numbers and apply this method to sort the elements

Using Pandas library with Random

Pandas is a popular data analysis library in Python. It has a built-in function called apply, which we can use to apply certain operations to all list elements. We can use the random library to generate random numbers and apply this method to sort the elements

grammar

DataFrame.apply(<function to apply to the elements>, axis=<0 for rows and 1
for columns> , raw=<boolean True or False> , result_type=None, other
parameters.....)
Copy after login

We can use the apply method on the Pandas data frame object. It takes the name of the function as a required parameter. This function is applied to all elements of the data frame. The axis parameter defines whether we want to use the function on rows or columns. convert_type is a Boolean value indicating whether to convert the data type of the resulting Series to a generic type inferred from the return value of the function

Example

的中文翻译为:

示例

我们在以下代码中首先导入了Pandas库,并使用pd作为别名。接下来,我们使用DataFrame方法创建了一个名为df的数据帧。我们对数据帧使用了apply方法,并使用generate_sorted_random_integers函数对所有数字进行处理。generate_sorted_random_integers函数使用了sampling方法来随机抽样一些数字,并使用sort方法对数字列表进行排序。

import pandas as pd
import random
df = pd.DataFrame({
    'start_range': [1, 1, 1],
    'end_range': [100, 100, 100],
    'num_elements': [10, 10, 10]
})
def generate_sorted_random_integers(row):
    random_list = random.sample(range(row[0], row[1] + 1), row[2])
    random_list.sort()
    return random_list
random_list = df[['start_range', 'end_range', 'num_elements']].apply(generate_sorted_random_integers, axis=1).tolist()
print(f"A multidimensional sorted list of random integers with unique elements are as follows: {random_list}")
Copy after login

输出

A multidimensional sorted list of random integers with unique elements are
as follows: [[11, 28, 31, 32, 35, 58, 73, 82, 88, 96], [17, 26, 42, 45, 47,
55, 89, 97, 99, 100], [26, 32, 66, 73, 74, 76, 85, 87, 93, 100]]
Copy after login

结论

在这篇文章中,我们了解了如何使用Python获取一个具有唯一元素的随机整数排序列表。random模块是生成随机数的最常用方法,因为它专门为此目的设计。然而,为了生成一个排序列表,我们还需要使用Python中的其他一些方法,比如choice、sample、lambda函数等。

The above is the detailed content of How to get a sorted list of random integers with unique elements using Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template