What does 'result[::-1]' mean?

最后都变了- 提交于 2019-11-30 18:37:51

It represents the 'slice' to take from the result. The first element is the starting position, the second is the end (non-inclusive) and the third is the step. An empty value before/after a colon indicates you are either starting from the beginning (s[:3]) or extending to the end (s[3:]). You can include actual numbers here as well, but leaving them out when possible is more idiomatic.

For instance:

In [1]: s = 'abcdefg'

Return the slice of the string that starts at the beginning and stops at index position 2:

In [2]: s[:3]
Out[2]: 'abc'

Return the slice of the string that starts at the third index position and extends to the end:

In [3]: s[3:]
Out[3]: 'defg'

Return the slice of the string that starts at the end and steps backward one element at a time:

In [4]: s[::-1]
Out[4]: 'gfedcba'

Return the slice of the string that contains every other element:

In [5]: s[::2]
Out[5]: 'aceg'

They can all be used in combination with each other as well. Here, we return the slice that returns every other element starting at index position 6 and going to index position 2 (note that s[:2:-2] would be more idiomatic, but I picked a weird number of letters :) ):

In [6]: s[6:2:-2]
Out[6]: 'ge'

The step element determines the elements to return. In your example, the -1 indicates it will step backwards through the item, one element at a time.

That's a common idiom that reverses a list.

a = ['a', 'b', 'c', 'd']
b = a[::-1]
print b

['d', 'c', 'b', 'a']

You can read about 'extended slices' here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!