搜尋
首頁後端開發Python教學Python程式將一個列表分成兩半

Python程式將一個列表分成兩半

Sep 19, 2023 pm 03:13 PM
清單分割 (list split)python 清單分割 (python list splitting)列表二分 (list bisection)

Python程式將一個列表分成兩半

在Python中,單一變數可以透過使用列表來包含多個項目。 Python 中用於儲存資料集合的四種內建資料類型之一是清單;另外三個是元組、集合和字典,每一個都有自己的用途。

什麼是列表?

方括號用於建立清單。 Python 中最有效的工具是列表,因為它們不一定是同類的。像整數、字串和物件這樣的資料類型都可以在一個列表中找到。由於清單是可變的,因此即使在建立清單之後也可以對其進行變更。

在本文中,我們將探索使用 Python 程式設計將清單分成兩半的各種方法。列表是可以儲存物件集合的可變資料類型之一。透過這些技巧,您將能夠輕鬆地將任何清單分成兩半!

使用切片技術

在第一個場景中,列表被分成兩半或兩半。根據列表的長度,這些一半的大小可以相等或不均勻。可以使用切片方法拆分清單。

演算法

  • 建立一個清單並使用其長度的一半初始化其中間索引。

  • 將其分成兩半,分別從開始到中間索引和從中間索引到結束。

  • 列印出原始清單以及各半清單。

  • 對每一半進行排序,然後將它們合併到一個排序的清單中。

  • 最後,列印出這個新的合併、排序清單。

範例

以下範例建立一個包含 6 個元素的列表,然後將索引設為 3。然後根據該索引將列表分成兩半 - 前半部是索引之前的所有元素,後半部是所有元素它後面的元素。最後,它印出列表的兩半。

#create list
list_1 = [10,20,30,40,50,60]
index = 3
first_half = list_1 [:index]
second_half = list_1 [index:]
print('The primary list is: ',list_1)
print("First half of list is ",first_half)
print("Second half of list is ",second_half)

輸出

The primary list is: [10, 20, 30, 40, 50, 60]
First half of list is [10, 20, 30]
Second half of list is [40, 50, 60]

在這裡,在上面解釋的方法中,我們預先定義了列表的索引和長度。如果沒有指定分割索引或兩部分的大小怎麼辦?下一步是確定清單的中間索引,這可以透過將清單的長度乘以 2 來完成。但是,如果列表的長度是奇數整數或列表不對稱,那麼當我們除以列表的長度時,我們將得到一個浮點值。列表。為了對結果進行四捨五入,我們將使用向下取整運算子 (//)。

範例

在這個方法中,我們主要關注的是解決一個不同的條件,即如果使用者要求的元素數量是奇數,那麼完成任務的過程是什麼。在這裡, split 函數傳回兩個不相等的列表,因為該列表具有奇數個元素。中間是 (5/2) = 2.5,因為列表有 5 項長。小於或等於除法結果的最接近的整數值由取整運算子傳回。在本例中,向下取整運算子產生 2,而不是 2.5。

演算法

  • 定義一個函數,該函數接受數字列表並要求使用者輸入值。

  • 使用 for 迴圈遍歷列表,

  • 然後使用append()函數將每個數字除以2並找到其中間索引。

  • 完成後提示使用者輸入。

#以下範例顯示程式將使用者輸入的數字清單分為兩半。它要求使用者輸入他們想要在清單中新增的元素數量,然後提示他們一次輸入一個元素。

中間索引的計算方法是將清單的長度除以2,然後使用該索引呼叫split_list() ,它使用切片來分隔前半部和清單的後半部分並分別傳回兩個列表。

def split_list(input_L,n):
   first_half = input_L[:n]
   second_half = input_L[n:]
return first_half,second_half
if __name__ == "__main__" :
   list_1 = []
   length = int(input("Enter the number of elements you want in list : "))
   for i in range(0, length):
      item = int(input("Enter the element for list "+str(i+1)+" :"))
      list_1.append (item)

   middle_index = length//2
   first,second = split_list (list_1,middle_index)
   print ("Primary list: ", list_1)
   print ("First half of the list is: ", first)
   print ("second half of the list is: ", second)

輸出

執行上述程式時,會產生以下輸出 -

Enter the number of elements you want in list: 5
Enter the element for list 1:98
Enter the element for list 2:60
Enter the element for list 3:45
Enter the element for list 4:33
Enter the element for list 5:55
Primary list: [98, 60, 45, 33, 55]
First half of the list is: [98, 60]
second half of the list is: [45, 33, 55]

結論

在本文中,我們使用 python 使用不同的方法將清單分成兩半。

以上是Python程式將一個列表分成兩半的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
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

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

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

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

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!