搜索
首页后端开发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

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

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)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言: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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具