切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[0:3])
print(L[:3])
print(L[-2:])#依然是从左到右
['Michael', 'Sarah', 'Tracy']
['Michael', 'Sarah', 'Tracy']
['Bob', 'Jack']
L = list(range(100))
print(L[:10])
print(L[-10:])
print(L[10:20])
print(L[:10:2])
print(L[::5])
print(L[:])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 2, 4, 6, 8]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
列表生成式
列表生成式在使用的时候先需要用中括号括住
[x * x for x in range(1, 11)]#生成1*1,2*2,...,10*10
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
加上条件判断
在某个条件下生成
[x*x for x in range(1,11) if x%2==0]
[4, 16, 36, 64, 100]
根据条件生成对应的东西
[x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
两层循环生成列表
[m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
在字典中使用列表生成式
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k+'='+v for k,v in d.items() ]
['x=A', 'y=B', 'z=C']
生成器
简介:如果列表很大 避免每次生成完整的列表 而是先根据需要生辰给其中的一部分
L = [x * x for x in range(10)]
print(L)
g = (x * x for x in range(10))#这个是列表生成器
print(g)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
<generator object <genexpr> at 0x000001E243330CC8>
g = (x * x for x in range(10))#for循环完成一次之后就会使得g没有内容
for n in g :
print(n,end = " ")
print('\n----for complete once----')
for n in g :
print(n,end = " ")
print('\n----for complete twice----')
0 1 4 9 16 25 36 49 64 81
----for complete once----
----for complete twice----
使用类似函数的方式构建生成器
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield(b)#改成print(b)正常的函数
a, b = b, a + b
n = n + 1
return 'done'
f = fib(6)
print(f)
for i in f:
print(i,end=" ")
<generator object fib at 0x000001E243330BC8>
1 1 2 3 5 8