搜尋
首頁後端開發Python教學如何使用Python獲取一個排序的隨機整數列表,其中元素唯一?

如何使用Python獲取一個排序的隨機整數列表,其中元素唯一?

產生隨機數字是程式設計、統計、機器學習模型等領域中最受歡迎的技術之一。產生一個具有唯一元素的排序隨機整數清單是這個任務的一個子領域。然而,計算機是確定性的機器,所以透過我們的實現產生隨機數只是有時一個明智的想法。在本文中,我們將探討如何使用Python來取得一個具有唯一元素的排序隨機整數清單。

使用隨機模組的範例函數

抽樣方法從給定的總體中產生k個元素的隨機樣本。它需要兩個必需的參數,第一個是元素列表,第二個是我們樣本列表中應該包含的元素數量。

文法

random.sample(iterable object, k)

函數sample接受兩個必要的參數:可迭代物件和結果中應該存在的元素數量。它將可迭代物件中的k個元素作為列表傳回。

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

此函數對可迭代物件進行排序。它以可迭代物件作為必需參數。我們也可以使用key參數設定元素的鍵。我們也可以使用reverse參數傳回排序後的可迭代物件的反向形式。

Example

的中文翻譯為:

範例

在下面的程式碼中,我們首先導入了Python的random模組。接下來,我們建立了generate_sorted_random_integers函數,它接受三個參數,分別是起始範圍、結束範圍和元素數量。我們使用range方法建立了一個整數範圍的列表,使用sample方法從中取出一些樣本,最後使用sorted方法對陣列進行排序。

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}")

輸出

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

使用Numpy模組

Numpy 是 Python 的一個流行的函式庫,用於數值計算。它還提供了創建隨機數的函數。我們可以利用 sort 方法對列表進行排序,利用 choice 方法來隨機抽取 k 個元素。

文法

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

Example

的中文翻譯為:

範例

在下面的範例中,導入Numpy函式庫後,我們定義了generate_sorted_random_integers函式。此函數以起始值、結束值和元素數量作為參數,並傳回一個隨機排序的清單。在函數下方,我們使用了range函數產生一個序列,choice方法從中選擇所需數量的元素,最後使用sort方法對列表進行排序。

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}")

輸出

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

使用列表推導和排序

列表推導是Python開發人員中流行的技術。這種方法的優點在於可以將邏輯語句、迭代表達式、條件表達式等組合在一行程式碼中,並根據它產生列表的元素。這有助於編寫一行程式碼的單一推導。

Example

的中文翻譯為:

範例

在下面的範例中,我們使用列表推導來建立一個排序的隨機數字列表。我們使用Python的random庫在所需範圍內建立隨機數,並使用sorted方法對隨機數列表進行排序。我們呼叫了使用者定義的函數,傳遞了必要的參數,並列印了結果。

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}")

輸出

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

使用Lambda函數

Lambda函數沒有任何名稱,如果程式碼行數較少,它們的行為類似於傳統函數。該函數可以接受參數並傳回值。然而,該函數沒有任何名稱。通常,當我們需要快速執行某些操作,並且確信這些操作不會在其他地方使用時,我們會使用這樣的函數。

Example 

的中文翻譯為:

範例 

在下面的程式碼中,我們使用了lambda函數,它以開始、結束和元素數量作為參數。此函數也使用列表推導式產生列表的元素。我們使用randint方法產生隨機數,並使用sorted方法對列表進行排序。

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}")

輸出

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

使用Lambda函數

Pandas是Python中流行的資料分析函式庫。它有一個內建函數叫做apply,我們可以用它來對所有列表元素應用某些操作。我們可以使用random函式庫產生隨機數,並應用此方法對元素進行排序

使用Pandas函式庫與Random

Pandas是Python中流行的資料分析函式庫。它有一個內建函數叫做apply,我們可以用它來對所有列表元素應用某些操作。我們可以使用random函式庫產生隨機數,並應用此方法對元素進行排序

文法

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

我們可以在Pandas的資料幀物件上使用apply方法。它以函數的名稱作為必需參數。此函數應用於資料幀的所有元素。 axis參數定義了我們是要在行還是列上使用該函數。 convert_type是一個布林值,指示是否將結果Series的資料類型轉換為從函數的傳回值推斷出的通用類型

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}")

输出

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

结论

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

以上是如何使用Python獲取一個排序的隨機整數列表,其中元素唯一?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器