1. 切片-原型是L[startIdx:endIdx:step]

  1. 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]
  1. step是负数:startIdx的值要大于endIdx的值

2. 迭代-主要是for...in的使用

  1. for ch in 'ABC'
  2. for i, value in enumerate(['A', 'B', 'C'])
  3. for x, y in [(1, 1), (2, 4), (3, 9)]

3. 列表生成式(list comprehension,listcomp)和生成器表达式(generator expression,genexp)

  1. listcomp用[]包括起来,genexp用()包括起来
  2. listcomp返回的是一个list,genexp返回的是一个iterator #### 4. 生成器函数 - 含有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])


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9, 11, 13]
[0, 2, 4, 6, 8, 10, 12, 14]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[14, 12, 10, 8, 6, 4, 2, 0]
[10, 9, 8, 7, 6, 5, 4, 3, 2]

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))


<generator object <genexpr> at 0x10d366678>
hello
world

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))


0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-17-62ccd2430fbd> in <module>()
     19 print(next(g))
     20 print(next(g))
---> 21 print(next(g))
     22 print(next(g))

StopIteration: 

In [ ]: