搜索
首页后端开发Python教程Python程序旋转列表元素

Python程序旋转列表元素

在Python中,可以使用列表来在单个变量中维护多个项目。列表是Python的四种内置数据类型之一,用于存储数据集合。另外三种类型,元组、集合和字典,各自具有不同的功能。列表使用方括号进行构造。由于列表不必是同质的,它们是Python中最有用的工具。一个列表可以包含字符串、对象和整数等数据类型。列表可以在生成后进行修改,因为它们是可变的。

本文的重点是速记和用一句话或一个词来表达这个概念的许多快捷方式。这个操作对于程序员来说非常重要,可以完成许多工作。我们将使用Python来展示四种不同的方法来完成这个任务。

Using The List Comprehension

在使用这种方法时,我们只需要在特定位置旋转后重新分配列表中每个元素的索引。由于其较小的实现,这种方法在完成任务中起着重要作用。

Algorithm

  • Defining a list first.

  • Use the list comprehension.

  • For applying two different sides right(i-index) and left(i+index).

  • Print the output list.

语法

#左旋转

list_1 = [list_1[(i + 3) % len(list_1)]

#For right rotate

list_1 = [list_1[(i - 3) % len(list_1)]

Example

Here, in this code we have used the list comprehension to rotate the elements in a list that is the right and left rotate. For loop is used to iterate through the list of elements.

list_1 = [10, 14, 26, 37, 42]
print (" Primary list : " + str(list_1))
list_1 = [list_1[(i + 3) % len(list_1)]
   for i, x in enumerate(list_1)]
print ("Output of the list after left rotate by 3 : " + str(list_1))
list_1 = [list_1[(i - 3) % len(list_1)]
   for i, x in enumerate(list_1)]
print ("Output of the list after right rotate by 3(back to primary list) : "+str(list_1))
list_1 = [list_1[(i + 2) % len(list_1)]
   for i, x in enumerate(list_1)]
print ("Output of the list after left rotate by 2 : " + str(list_1))
list_1 = [list_1[(i - 2) % len(list_1)]
   for i, x in enumerate(list_1)]
print ("Output of the list after right rotate by 2 : "+ str(list_1))

输出

Primary list : [10, 14, 26, 37, 42]
Output of the list after left rotate by 3 : [37, 42, 10, 14, 26]
Output of the list after right rotate by 3(back to primary list) : [10, 14, 26, 37, 42]
Output of the list after left rotate by 2 : [26, 37, 42, 10, 14]
Output of the list after right rotate by 2 : [10, 14, 26, 37, 42]

Here, in this code we have used the list comprehension to rotate the elements in a list that is the right and left rotate. For loop is used to iterate through the list of elements.

使用切片

This specific technique is the standard technique. With the rotation number, it simply joins the later-sliced component to the earlier-sliced part.

Algorithm

  • Defining a list first.

  • Use slicing method.

  • 在右旋和左旋后打印每个列表。

语法

FOR SLICING

#左旋转 -

list_1 = list_1[3:] + list_1[:3]

#右旋转 -

list_1 = list_1[-3:] + list_1[:-3]

Example

The following program rearranges the elements of a list. The original list is [11, 34, 26, 57, 92]. First rotate 3 units to the left. That is, the first three elements are moved to the end, resulting in [57, 92, 11, 34, 26]. Then rotate right by 3 so the last three elements move back and forth to their original positions [11,34,26,57,92].

然后向右旋转2次,使最后两个元素向前移动,得到 [26, 57, 92, 11, 34]。最后向左旋转1次,将一个元素从开头移到末尾,得到 [57, 92, 11, 34, 26]。

list_1 = [11, 34, 26, 57, 92]
print (" Primary list : " + str(list_1))
list_1 = list_1[3:] + list_1[:3]
print ("Output of the list after left rotate by 3 : " + str(list_1))
list_1 = list_1[-3:] + list_1[:-3]
print ("Output of the list after right rotate by 3(back to Primary list) : "+str(list_1))
list_1 = list_1[-2:] + list_1[:-2]
print ("Output of the list after right rotate by 2 : "+ str(list_1))
list_1 = list_1[1:] + list_1[:1]
print ("Output of the list after left rotate by 1 : " + str(list_1))

输出

Primary list : [11, 34, 26, 57, 92]
Output of the list after left rotate by 3 : [57, 92, 11, 34, 26]
Output of the list after right rotate by 3(back to Primary list) : [11, 34, 26, 57, 92]
Output of the list after right rotate by 2 : [57, 92, 11, 34, 26]
Output of the list after left rotate by 1 : [92, 11, 34, 26, 57]

Using The Numpy Module

使用给定的轴,我们还可以使用python中的numpy.roll模块来旋转列表中的元素。输入数组的元素会因此被移动。如果一个元素从第一个位置移动到最后一个位置,它会回到初始位置。

Algorithm

  • 导入numpy.roll模块

  • Define the list and give the particular index.

  • Print the output list.

Example

A list 'number' is created and assigned the values 1, 2, 4, 10, 18 and 83. The variable i is set to 1. The np.roll() function from the NumPy library is then used on the list number with an argument of i which shifts each element in the list by 1 index position (the first element becomes last).

import numpy as np
if __name__ == '__main__':
   number = [1, 2, 4, 10, 18, 83]
   i = 1
   x = np.roll(number, i)
   print(x)

输出

[83 1 2 4 10 18]

Usingcollections.deque.rotate()

rotate()函数是由collections模块中的deque类提供的内置函数,用于实现旋转操作。尽管不太为人所知,但这个函数更加实用。

Algorithm

  • 首先从collection模块导入deque类。

  • 定义一个列表

  • 打印主要列表

  • 使用rotate()函数旋转元素

  • Print the output.

Example

The following program uses the deque data structure from the collections module to rotate a list. The original list is printed, then it rotates left by 3 and prints out the new rotated list. It then rotates right (back to its original position) by 3 and prints out the resulting list.

from collections import deque
list_1 = [31, 84, 76, 97, 82]
print ("Primary list : " + str(list_1))
list_1 = deque(list_1)
list_1.rotate(-3)
list_1 = list(list_1)
print ("Output list after left rotate by 3 : " + str(list_1))
list_1 = deque(list_1)
list_1.rotate(3)
list_1 = list(list_1)
print ("Output list after right rotate by 3(back to primary list) : "+ str(list_1))

输出

Primary list : [31, 84, 76, 97, 82]
Output list after left rotate by 3 : [97, 82, 31, 84, 76]
Output list after right rotate by 3(back to primary list) : [31, 84, 76, 97, 82]

结论

在本文中,我们简要解释了四种不同的方法来旋转列表中的元素。

以上是Python程序旋转列表元素的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

您如何在python列表中访问元素?您如何在python列表中访问元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

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

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

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SecLists

SecLists

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

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具