首页 > python中list的截取

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?


你好:
我在我的3.4.3下测试了一下,第二个输出应该是['foo5', 'foo4', 'foo3', 'foo2']

在python的文档中说,[i:j:step]中i或者是j如果大于len(l)的话,那么会变为len(l)。对于slice的上下界python文档里也是明确说明了包含起始位置,不包含结束位置。那么这样一来你的l[len(L):0:-1]确实是会越界,但是结果并没有。我想这可能是python的一个小问题。

但是list提供了一个reverse方法可以很方便的实现你的要求


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+2k, i+3k 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])
【热门文章】
【热门文章】