python中list的截取
L = ['foo1', 'foo2', 'foo3', 'foo4', 'foo5']
print(L[::])
print(L[::-1])
上面这段代码分别正向和反向输出了整个list,然后我想显式的限定上下限来输出list,
print(L[0:len(L)])
print(l[len(L):0:-1])
这样会输出:
['foo1', 'foo2', 'foo3', 'foo4', 'foo5']
['foo4', 'foo3', 'foo2', 'foo1']
根据第一个输出看起来感觉L[]语法中的范围是包含下限但不包括上限的list,但如果是这样,第二个中的
len(L)
应该会越界。所以L[]的语法规则到底是什么样的?还有怎样才能反向输出整个list?
Answers
5.6. Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange
The slice of s from i to j with step k is defined as the sequence of
items with index x = i + n*k such that 0 <= n < (j-i)/k. In other
words, the indices are i, i+k, i+2 k, i+3 k and so on, stopping when j
is reached ( but never including j ). If i or j is greater than len(s),
use len(s). If i or j are omitted or None, they become “end” values
(which end depends on the sign of k). Note, k cannot be zero. If k is
None, it is treated like 1.
逆向输出
print(L[-1:-len(L)-1:-1])