使用切片表示法反转列表 [英] Reversing a list using slice notation

查看:32
本文介绍了使用切片表示法反转列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中:

foo = ['red', 'white', 'blue', 1, 2, 3]

where: foo[0:6:1] 将打印 foo 中的所有元素.但是,foo[6:0:-1] 将省略第 1 个或第 0 个元素.

<预><代码>>>>foo[6:0:-1][3, 2, 1, '蓝色', '白色']

我知道我可以使用 foo.reverse() 或 foo[::-1] 来反向打印列表,但我试图理解为什么 foo[6:0:-1] 不打印整个列表?

解决方案

切片符号简写:

[ <要包含的第一个元素>:<要排除的第一个元素>:<步骤>]

如果要在反转列表时包含第一个元素,请将中间元素留空,如下所示:

foo[::-1]

您还可以在此处找到一些关于 Python 切片的一般信息:
解释 Python 的切片符号

in the following example:

foo = ['red', 'white', 'blue', 1, 2, 3]

where: foo[0:6:1] will print all elements in foo. However, foo[6:0:-1] will omit the 1st or 0th element.

>>> foo[6:0:-1]
[3, 2, 1, 'blue', 'white']

I understand that I can use foo.reverse() or foo[::-1] to print the list in reverse, but I'm trying to understand why foo[6:0:-1] doesn't print the entire list?

解决方案

Slice notation in short:

[ <first element to include> : <first element to exclude> : <step> ]

If you want to include the first element when reversing a list, leave the middle element empty, like this:

foo[::-1]

You can also find some good information about Python slices in general here:
Explain Python's slice notation

这篇关于使用切片表示法反转列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆