如何在Python中反转数组

2024-05-17 10:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中 如何编写以下程序:

从一个数组中,按照给定的顺序将单词从中间向两边反转并显示

InputArray = ['Good', 'better', 'Best', 'Fanstatic', 'perfect', 'Super', 'Fine', 'Great' ]

Output = [ 'Fanstatic', 'Best', 'Better', 'Good', 'Great', 'Fine', 'Super', 'Perfect' ]

Tags: 程序output顺序数组fanstatic单词bestgood
3条回答

使用reverse()函数

>>> InputArray = ['Good', 'better', 'Best', 'Fantastic', 'perfect', 'Super', 'Fine', 'Great']
>>> middle = len(InputArray)/2
>>> Output = InputArray[middle:] + InputArray[:middle] # swap the last half with the first half
>>> Output.reverse() # reverse the list in-place
>>> Output
['Fantastic', 'Best', 'better', 'Good', 'Great', 'Fine', 'Super', 'perfect']

说明:

InputArray[middle:]返回从索引middle到结尾的子列表 InputArray[:middle]返回从索引0到middle - 1的子列表

或者你可以用这一层

^{pr2}$

说明:

InputArray[middle-1::-1]返回从索引middle-1到0的子列表
InputArray[:middle-1:-1]返回从index end到middle - 1的子列表

[start:end:step_size]第三个参数将步长设置为-1,因此顺序相反。在

m = len(InputArray)/2
OutputArray = InputArray[0:m][::-1]+InputArray[m::][::-1]

给定输入的输出:

^{pr2}$
l1 = ['Good', 'better', 'Best', 'Fanstatic', 'perfect', 'Super', 'Fine', 'Great']
hlength = len(l1)//2
print inputArray[:hlength][::-1] + inputArray[hlength:][::-1]

输出

^{pr2}$

相关问题 更多 >