L[startIdx:endIdx:step]
startIdx 存在 |
endIdx 存在 |
step 存在 |
形式 | L = list(range(15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |
---|---|---|---|---|
Y | Y | Y | L[1:10:2] | [1, 3, 5, 7, 9] |
N | Y | Y | L[:10:2] | [0, 2, 4, 6, 8] |
Y | N | Y | L[1::2] | [1, 3, 5, 7, 9, 11, 13] |
N | N | Y | L[::2] | [0, 2, 4, 6, 8, 10, 12, 14] |
Y | Y | N | L[1:10] | [1, 2, 3, 4, 5, 6, 7, 8, 9] |
N | Y | N | L[:10] | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Y | N | N | L[1:] | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |
N | N | N | L[:] | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |
for ch in 'ABC'
for i, value in enumerate(['A', 'B', 'C'])
for x, y in [(1, 1), (2, 4), (3, 9)]
yield
关键字的函数,可以使用next()函数来获取下一个输出(statefulness)
#### 5. itertools
In [9]:
L = list(range(15))
print(L)
print(L[1:10:2])
print(L[:10:2])
print(L[1::2])
print(L[::2])
print(L[1:10])
print(L[:10])
print(L[1:])
print(L[:])
print(L[::-2])
print(L[10:1:-1])
In [14]:
# 列表生成式
L = ['Hello', 'World', 18, 'Apple', 'None']
# 生成器表达式
g = (s.lower() for s in L if isinstance(s, str))
print(g)
print(next(g))
print(next(g))
In [17]:
def get15():
for x in range(15):
yield x
g = get15()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
In [ ]: