切片 #
[start:end:step]
遍历 #
enumerate #
a = ["a", "b", "c", "d"]
# index & value
for i in xrange(len(a)):
print i, a[i]
# iterate with index
for i, el in enumerate(a):
print i, el
# i 从 1 开始
for i, el in enumerate(a, 1):
print i, el
step 为负数 #
最后一个字符到下标是 -1,即从右到左,是从 -1 开始,然后 -1、-2、-3、-4、-5
字符串反转 #
letter[::-1]
为什么 s[:-1:-1] 是空 #
只需要记住,s[start:end:step] 就行,包括 start,不包括 end, 所以,如果要实现:去掉最后一个元素,然后再倒序,应该是:
- 倒数第二个作为 start,end 默认,step 是 -1
- 也就是:
s[-2::-1]
s[i:j:k]
-
If i or j is negative, the index is relative to the end of sequence s:
len(s) + i
orlen(s) + j
is substituted.- But note that -0 is still 0.
-
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.
-
the indices are i, i+k, i+2k, i+3k and so on,
- stopping when j is reached (but never including j).
-
When k is positive, i and j are reduced to len(s) if they are greater.
-
When k is negative, i and j are reduced to len(s) - 1 if they are greater.
-
If i or j are omitted or None, they become “end” values (which end depends on the sign of k).
-
k cannot be zero.
- If k is None, it is treated like 1.
-
s[:]
- 等同于
s[::]
- 等同于
s[None:None:None]
- 等同于
s[0:len(s):1]
- 等同于
-
s[::-1]
- 等同于
s[None:None:-1]
- 等同于
s[len(s)-1:-len(s)-1:-1]
- 包括 start,所以 start 从
len(s)-1
开始, 就是 s[-1] - 不包括 end, 所以 end 到
-len(s)-1
, 实际上就是到-len(s)
, 也就是 s[0]
- 包括 start,所以 start 从
- 等同于
-
s[:-1:-1]
- 等同于
s[len(s)-1:-1:-1]
- 等同于
s[len(s)-1:len(s)-1:-1]
- 等同于
参考:
sequence 乘法 #
s * n
或n * s
- equivalent to adding s to itself n times
- items in the sequence s are not copied
- they are referenced multiple times
- Values of n less than 0 are treated as 0
- which yields an empty sequence of the same type as s
- equivalent to adding s to itself n times
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
叶王 © 2013-2024 版权所有。如果本文档对你有所帮助,可以请作者喝饮料。