2009年10月19日 星期一

[Python] Slicing on sequences

今天在 comp.lang.python 的討論裡看到一篇 Reverse Iteration Through Integers
,提到 list[::-1] 的用法,就找了一下 python docs

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j.

When used as an expression, a slice is a sequence of the same type.

This implies that the index set is renumbered so that it starts at 0.

Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.



所以 a[::-1]  的 index X 會由 X = 0+1*(-1) = -1,X = 0+2*(-1) = -2 這樣慢慢往回跑

Test code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
a = 123450
print "a=",a,"\t type = ",type(a)
b = str(a)
print "b=",b,"\t type = ",type(b)
c = b[::-1]
print "c=",c,"\t type = ",type(c)
d = int(c)
print "d=",d,"\t type = ",type(d)

沒有留言: